package com.yulian.web_api.report;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.healthmarketscience.sqlbuilder.Conditions;
import com.healthmarketscience.sqlbuilder.CustomSql;
import com.healthmarketscience.sqlbuilder.InCondition;
import com.healthmarketscience.sqlbuilder.SelectQuery;
import com.yulian.repository.CommonRepositoryImpl;
import com.yulian.util.CommonUtils;

import com.yulian.util.TimeUtils;
import com.yulian.web_api.vo.InitialBatchDetailVo;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.Tuple;

/**
 * 该类位于业务逻辑层，主要实现供应商批次商品进销存管理，为MainVerticle中的REST接口提供服务
 *
 * @author
 */
public class SupplierBatchGoodspsiManager {
    final InternalLogger logger = Log4JLoggerFactory.getInstance(SupplierBatchGoodspsiManager.class);
    CommonRepositoryImpl commonRepository = new CommonRepositoryImpl();

    /**
     * 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecords(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传递的字段
        List<String> must_fields = Arrays.asList("big_area_id_list", "site_id_list", "warehouse_id_list", "aggregation_id_list");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        }
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明
        String big_area_id_list = bodyJSObj.getString("big_area_id_list");
        String site_id_list = bodyJSObj.getString("site_id_list");
        String warehouse_id_list = bodyJSObj.getString("warehouse_id_list");
        String aggregation_id_list = bodyJSObj.getString("aggregation_id_list");
        String supplier_pickup_goods_inspect_accept_codes = bodyJSObj.getString("supplier_pickup_goods_inspect_accept_codes");
        String processing_date = bodyJSObj.getString("processing_date");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();
        queryJSObj.put("big_area_id", big_area_id_list);
        queryJSObj.put("site_id", site_id_list);
        queryJSObj.put("warehouse_id", warehouse_id_list);
        queryJSObj.put("aggregation_id", aggregation_id_list);
        if (!processing_date.equals("") && processing_date!=null){
            queryJSObj.put("processing_date", processing_date);
        }
        List<String> stringList =new ArrayList<>();
        if (!supplier_pickup_goods_inspect_accept_codes.equals("") && supplier_pickup_goods_inspect_accept_codes!=null){
             stringList = List.of(supplier_pickup_goods_inspect_accept_codes.split(","));
        }

        List<String> finalStringList = stringList;
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //用于传递给构建sql的JsonObject
            String sql = createSelectSql(queryJSObj, query_offset, query_limit);
            //获取满足条件的记录总数
            Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsSupplierBatchGoodsPsi");
            CompositeFuture.join(Arrays.asList( future )).onComplete(ar2 -> {
                if (ar2.succeeded()) {
                    JsonObject dataJSObj = new JsonObject();
                    JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(0);
                    List<JsonObject> jsonObjectList = new ArrayList<>();
                    for (int i = 0 ; i < recordsJSArray.size();i++){
                        JsonObject jsonObject =   recordsJSArray.getJsonObject(i);
                        if (finalStringList.size()>0){
                            String str = jsonObject.getString("supplier_pickup_goods_inspect_accept_codes")==null? "":jsonObject.getString("supplier_pickup_goods_inspect_accept_codes");
                            for (String str1 : finalStringList){
                                if (str.contains(str1)){
                                    //包含则是要的数据
                                    jsonObjectList.add(jsonObject);
                                    break;
                                }
                            }
                        }else {
                            //该条件没有值 则不需要这个条件过滤
                            jsonObjectList.add(jsonObject);
                        }
                    }
                    dataJSObj.put("total", jsonObjectList.size()).put("records",jsonObjectList);
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                } else {
                    logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                    promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsSupplierBatchGoodsPsi", "获取进销存数据失败"));
                }
            });
        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsSupplierBatchGoodsPsi", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSql(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("b.id"),new CustomSql("b.supply_chain_goods_weight_package_spec"),new CustomSql("b.supplier_pickup_goods_inspect_accept_codes"),
        new CustomSql("(select h.big_area_name   from big_area h where h.is_delete=0  and h.id=b.big_area_id ) as big_area_name"),
        new CustomSql("(select h.site_name  from site h   where h.is_delete=0   and h.id=b.site_id ) as site_name"),
        new CustomSql("warehouse_id"),new CustomSql("(select w.warehouse_name " +
                                "from warehouse w " +
                                "where w.is_delete=0 " +
                                "and w.id=b.warehouse_id limit 1 ) as warehouse_name "),
        new CustomSql("aggregation_id"),
        new CustomSql("(select ag.aggregation_name " +
                "from  aggregation_goods ag " +
                "where ag.is_delete=0 " +
                "and id=b.aggregation_id limit 1 ) as aggregation_name"),
        new CustomSql("(select ( " +
                "           select  a.type_name " +
                "           from sales_package_spec_type a " +
                "           where a.is_delete=0 " +
                "           and a.id =gp.sales_package_spec_type_id " +
                "           limit 1 ) as type_name " +
                " from goods_parameter gp " +
                " where gp.is_delete=0 " +
                "  and gp.aggregation_id=b.aggregation_id limit 1) as type_name"),
        new CustomSql("( select  a.class_name   from goods_class_lv1 a  where a.is_delete=0 and a.id =b.class_lv1_id limit 1 ) as class1_name"),
        new CustomSql("( select  a.class_name   from goods_class_lv2 a  where a.is_delete=0 and a.id =b.class_lv2_id limit 1 ) as class2_name"),
         new CustomSql("(select (  " +
                 "                           select  a.goods_gather_area_name   " +
                 "                           from goods_gather_area a   " +
                 "                           where a.is_delete=0   " +
                 "                           and a.id =gp.goods_gather_area_id  " +
                 "                           limit 1 ) as  goods_gather_area_name   " +
                 "                 from goods_parameter gp   " +
                 "             where gp.is_delete=0   " +
                 "                  and gp.aggregation_id=b.aggregation_id limit 1) as goods_gather_area_name"),
        new CustomSql("( select  a.class_name  from goods_variety a  where a.is_delete=0  and a.id =b.variety_id  limit 1 ) as variety_name "),
        new CustomSql("(select  (select c.list_package_spec " +
                "         from goods_parameter_list_goods c " +
                "         where  c.is_delete=0 " +
                "           and c.id=gp.goods_parameter_list_goods_id limit 1 ) as list_package_spec " +
                " from goods_parameter gp " +
                " where gp.is_delete=0 " +
                "  and gp.aggregation_id=b.aggregation_id limit 1) as list_package_spec"),
        new CustomSql("(select         (select c.sales_package_spec " +
                "                from goods_parameter_list_goods c " +
                "                where  c.is_delete=0 " +
                "                  and c.id=gp.goods_parameter_list_goods_id limit 1 ) as sales_package_spec " +
                " from goods_parameter gp " +
                " where gp.is_delete=0 " +
                "  and gp.aggregation_id=b.aggregation_id limit 1 ) as sales_package_spec"),
        new CustomSql("(select sum(ibd.end_inventory_number) as end_inventory_number from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as end_inventory_number "),
        new CustomSql("(select sum(ibd.end_inventory_weight) as end_inventory_weight from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as end_inventory_weight "),
        new CustomSql("(select sum(ibd.inventory_number) as inventory_number from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as inventory_number "),
        new CustomSql("(select sum(ibd.inventory_weight) as inventory_weight from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as inventory_weight "),
        new CustomSql("(select sum(ibd.accept_number) as accept_number from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as accept_number "),
        new CustomSql("(select sum(ibd.accept_weight) as accept_weight from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as accept_weight "),
        new CustomSql("(select sum(ibd.loss_number) as loss_number from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as loss_number "),
        new CustomSql("(select sum(ibd.loss_weight) as loss_weight from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as loss_weight "),
        new CustomSql("(select sum(ibd.profit_loss_number) as profit_loss_number from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as profit_loss_number "),
        new CustomSql("(select sum(ibd.profit_loss_weight) as profit_loss_weight from initial_batch_detail ibd where ibd.is_delete=0 and ibd.supply_chain_goods_id in (select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id) and ibd.warehouse_id=b.warehouse_id " +
                 " and ibd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and ibd.time_line=b.time_line )as profit_loss_weight "),
        new CustomSql("(select sum(srwd.retrun_warehouse_weight) from sales_return_warehouse_detail srwd where srwd.is_delete=0 and srwd.warehouse_id=b.warehouse_id and srwd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and srwd.delivery_date=b.time_line and srwd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp  where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as retrun_warehouse_weight"),
        new CustomSql("(select sum(srwd.retrun_warehouse_number) from sales_return_warehouse_detail srwd where srwd.is_delete=0 and srwd.warehouse_id=b.warehouse_id and srwd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and srwd.delivery_date=b.time_line and srwd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp  where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as retrun_warehouse_number"),
        new CustomSql("(select sum(sdpcd.shift_delivery_plan_completion_number) from shift_delivery_plan_completion_detail sdpcd where sdpcd.is_delete=0 and sdpcd.warehouse_id=b.warehouse_id and sdpcd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and sdpcd.delivery_date=b.time_line and sdpcd.supply_chain_goods_id in " +
                "( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id ) ) as shift_delivery_plan_completion_number"),
        new CustomSql("(select sum(sdpcd.shift_delivery_plan_completion_weight) from shift_delivery_plan_completion_detail sdpcd where sdpcd.is_delete=0 and sdpcd.warehouse_id=b.warehouse_id and sdpcd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and sdpcd.delivery_date=b.time_line and sdpcd.supply_chain_goods_id in " +
                "( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id ) ) as shift_delivery_plan_completion_weight"),
        new CustomSql("(select sum(pcd.pickup_number) from pickup_completion_detail pcd where pcd.is_delete=0 and pcd.warehouse_id=b.warehouse_id and pcd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and pcd.trade_date=b.time_line " +
                "  and pcd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as pickup_number"),
        new CustomSql("(select sum(pcd.pickup_weight) from pickup_completion_detail pcd where pcd.is_delete=0 and pcd.warehouse_id=b.warehouse_id and pcd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec and pcd.trade_date=b.time_line " +
                "  and pcd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as pickup_weight"),
        new CustomSql("(select sum(prd.purchase_return_weight) from purchase_return_detail prd where prd.is_delete=0 and prd.warehouse_id=b.warehouse_id and prd.purchase_return_date=b.time_line  and  prd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec " +
                "  and prd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as purchase_return_weight"),
        new CustomSql("(select sum(prd.purchase_return_number) from purchase_return_detail prd where prd.is_delete=0 and prd.warehouse_id=b.warehouse_id and prd.purchase_return_date=b.time_line and  prd.supply_chain_goods_settle_package_spec=b.supply_chain_goods_settle_package_spec " +
                "  and prd.supply_chain_goods_id in ( select gp.supply_chain_goods_id from goods_parameter gp where gp.is_delete=0 and gp.aggregation_id=b.aggregation_id )) as purchase_return_number"),
                        new CustomSql("b.time_line"), new CustomSql("b.supply_chain_goods_settle_package_spec"), new CustomSql("b.supplier_pickup_goods_inspect_accept_id"),
        new CustomSql("b.sales_supplier_pickup_goods_inspect_accept_id"),
        new CustomSql("b.is_delete"), new CustomSql("b.create_user"), new CustomSql("b.update_user"), new CustomSql("b.create_time"), new CustomSql("b.update_time"))
        .addCustomFromTable("supplier_batch_goods_psi b");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if ("processing_date".equals(key)) {
                    sq.getWhereClause().addCustomCondition(Conditions.equalTo(new CustomSql("time_line"),
                            TimeUtils.parseLocalDate(value, "yyyy-MM-dd")).setDisableParens(true));
                    continue;
                }
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() +" order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看期初明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForInitialBatchDetial(PgPool client, JsonObject config, JsonObject bodyJSObj) throws ParseException {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String time_line = bodyJSObj.getString("time_line");

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse(time_line);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        // 把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(Calendar.DATE, 1);
        // 这个时间就是日期往后推一天的结果
        Date date2 = calendar.getTime();
        SimpleDateFormat formats=new SimpleDateFormat("yyyy-MM-dd");
        String time_line2=formats.format(date2);
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;

        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detial 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> list_goods_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();
        Set<String> sales_package_spec_type_id_list_set = new HashSet<String>();

        //首先根据聚合商品名获取对应的供应链商品名
        ArrayList<String> supply_chain_goods_id_list = new ArrayList<>();

//        supply_chain_goods_id_list.add("[");
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                String stra ="";
                if (resJSArray1.size()==0){
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }else {
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        if (i==0){
                            stra=jsonObj.getString("supply_chain_goods_id");
                        }else {
                            stra=stra+","+jsonObj.getString("supply_chain_goods_id");

                        }
                    }
//                    supply_chain_goods_id_list.add("]");

                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    queryJSObj.put("supply_chain_goods_id", String.join(",", supply_chain_goods_id_list));
                    queryJSObj.put("supply_chain_goods_settle_package_spec", supply_chain_goods_settle_package_spec);
                    queryJSObj.put("time_line", time_line2);  //查询昨天的初期库存数据的 期末值 作为查询今天的初期库存值
                    queryJSObj.put("is_delete", 0);

                    String sql = createSelectSqlForInitialBatchDetial(queryJSObj, query_offset, query_limit);

                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "initial_batch_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "get_list_goods_batch_goods_psi");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getInitialBatchDetialRecords");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getSupplierBatchGoodspsiRecords", "获取供应商批次商品进销存参数失败"));
                        }
                    });
                }
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getSupplyChainGooodsIdRecords", "获取供应链商品参数失败")));
        }).
        onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getSupplierBatchGoodspsiRecords", "数据库连接失败")));
        return promise.future();
    }


    /**
     * 创建查询符合搜索条件记录的sql语句——查看期初明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForInitialBatchDetial(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supply_chain_goods_id"), new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("goods_batch_code"),
        new CustomSql("supplier_id"), new CustomSql("real_settlement_price"), new CustomSql("transport_price"), new CustomSql("land_price"),
        new CustomSql("end_inventory_number as inventory_number"),new CustomSql("  (select a.supply_chain_goods_name " +
                                "        from supply_chain_goods a " +
                                "        where a.is_delete=0 " +
                                "        and  a.id=supply_chain_goods_id) as supply_chain_goods_name "),
                        new CustomSql("     (select b.supplier_name " +
                                "        from supplier_info b " +
                                "        where b.is_delete=0 " +
                                "          and b.id=supplier_id) as supplier_name "),
                        new CustomSql("  (select w.warehouse_name " +
                                "        from warehouse w " +
                                "        where w.is_delete=0 " +
                                "          and w.id=warehouse_id) as warehouse_name "),
                        new CustomSql("end_inventory_weight as inventory_weight"), new CustomSql("time_line"),new CustomSql("end_inventory_amount as inventory_land_acount"), new CustomSql("warehouse_id"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("initial_batch_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }


    /**
     * 查看销售退库入库单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForSalesReturnWarehouseDetial(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String time_line = bodyJSObj.getString("time_line");
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;

        JsonObject queryJSObj = new JsonObject();

        //首先根据聚合商品名获取对应的供应链商品名
        Set<Integer> supplys= new HashSet<>();
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                if (resJSArray1.size()==0){
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }else {
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        Integer a = Integer.valueOf(jsonObj.getString("supply_chain_goods_id"));
                        supplys.add(a);
                    }
//                    supply_str.set(supply_str + "]");
                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    String supply_str="";
                    Integer[] array = supplys.toArray(new Integer[supplys.size()]);
                    for (int i = 0 ; i < array.length ; i ++){
                        if (i==0){
                            supply_str=supply_str+array[i];
                        }else {
                            supply_str=supply_str+","+array[i];
                        }
                    }
                    queryJSObj.put("supply_chain_goods_id", supply_str);
                    queryJSObj.put("supply_chain_goods_settle_package_spec", supply_chain_goods_settle_package_spec);
                    queryJSObj.put("is_delete", 0);
                    queryJSObj.put("delivery_date", time_line);
                    String sql = createSelectSqlForSalesReturnWarehouseDetail(queryJSObj, query_offset, query_limit);

                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "sales_return_warehouse_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForSalesReturnWarehouseDetial");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForSalesReturnWarehouseDetial");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForSalesReturnWarehouseDetial", "获取销售退货入库单明细失败"));
                        }
                    });
                }
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getRecordsForSalesReturnWarehouseDetial", "获取销售退货入库单明细失败")));
        }).
        onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForSalesReturnWarehouseDetial", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看销售退库入库单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSalesReturnWarehouseDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("delivery_date"), new CustomSql("shift_delivery_plan_code"), new CustomSql("sales_return_warehouse_code"),
        new CustomSql("list_goods_id"),new CustomSql("( select lg.list_goods_name " +
                                "from list_goods lg where lg.is_delete=0 and lg.id=list_goods_id ) as list_goods_name"),
        new CustomSql("list_package_spec"), new CustomSql("sales_package_spec_id"),
        new CustomSql("(select spst.package_spec_name from sales_package_spec spst where spst.is_delete=0 " +
                "and spst.id=sales_package_spec_id ) as package_spec_name"),
        new CustomSql("goods_batch_code"), new CustomSql("supply_chain_goods_id"),
        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "),
        new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("buyer_name"), new CustomSql("buyer_id"), new CustomSql("order_code"), new CustomSql("retrun_number"), new CustomSql("warehouse_id"),
        new CustomSql("retrun_weight"), new CustomSql("retrun_warehouse_weight"), new CustomSql("retrun_warehouse_number"), new CustomSql("return_loss_number"), new CustomSql("return_loss_weight"),
        new CustomSql("is_delete"),new CustomSql("supplier_id"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("sales_return_warehouse_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看车次配送计划完工单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForShiftDeliveryPlanCompletionDetail(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表list_goods_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String delivery_date = bodyJSObj.getString("delivery_date");
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detail 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> list_goods_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();
        Set<String> sales_package_spec_type_id_list_set = new HashSet<String>();
        //首先根据聚合商品名获取对应的供应链商品名
        Set<Integer> supplys= new HashSet<>();
        //        supply_chain_goods_id_list.add("[");
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                if (resJSArray1.size()==0){
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }else {
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        Integer a = Integer.valueOf(jsonObj.getString("supply_chain_goods_id"));
                        supplys.add(a);
                    }
//                    supply_chain_goods_id_list.add("]");
                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    String supply_str="";
                    Integer[] array = supplys.toArray(new Integer[supplys.size()]);
                    for (int i = 0 ; i < array.length ; i ++){
                        if (i==0){
                            supply_str=supply_str+array[i];
                        }else {
                            supply_str=supply_str+","+array[i];
                        }
                    }
                    queryJSObj.put("supply_chain_goods_id", supply_str);
                    queryJSObj.put("supply_chain_goods_settle_package_spec", supply_chain_goods_settle_package_spec);
                    queryJSObj.put("is_delete", 0);
                    queryJSObj.put("delivery_date", delivery_date);
                    String sql = createSelectSqlForShiftDeliveryPlanCompletionDetail(queryJSObj, query_offset, query_limit);
                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "shift_delivery_plan_completion_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForShiftDeliveryPlanCompletionDetail");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForShiftDeliveryPlanCompletionDetail");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForShiftDeliveryPlanCompletionDetail", "获取车次配送计划完工单明细失败"));
                        }
                    });
                }
            }).
            onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForShiftDeliveryPlanCompletionDetail", "数据库连接失败")));
        });
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看车次配送计划完工单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForShiftDeliveryPlanCompletionDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("delivery_date"), new CustomSql("shift_delivery_plan_code"), new CustomSql("shift_delivery_plan_completion_code"),
        new CustomSql("list_goods_id"), new CustomSql("( select lg.list_goods_name " +
                                "from list_goods lg where lg.is_delete=0 and lg.id=list_goods_id ) as list_goods_name"),
                        new CustomSql("(select spst.package_spec_name from sales_package_spec spst where spst.is_delete=0 " +
                                "and spst.id=sales_package_spec_id ) as package_spec_name"),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "),
        new CustomSql("list_package_spec"), new CustomSql("sales_package_spec_id"),
        new CustomSql("goods_batch_code"), new CustomSql("supply_chain_goods_id"),
        new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("buyer_name"), new CustomSql("buyer_id"), new CustomSql("order_code"), new CustomSql("order_number"),
        new CustomSql("order_weight"), new CustomSql("shift_delivery_plan_number"), new CustomSql("shift_delivery_plan_completion_number"), new CustomSql("diff_number"),
        new CustomSql("shift_delivery_plan_weight"), new CustomSql("shift_delivery_plan_completion_weight"), new CustomSql("diff_weight"), new CustomSql("warehouse_id"),
        new CustomSql("is_delete"), new CustomSql("supplier_id"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("shift_delivery_plan_completion_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }


    /**
     * 查看自提完工单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForPickupCompletionDetail(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表list_goods_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String trade_date=bodyJSObj.getString("trade_date");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();

        //首先根据聚合商品名获取对应的供应链商品名
        Set<Integer> supplys= new HashSet<>();
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                if (resJSArray1.size()==0){
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }else {
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        Integer a = Integer.valueOf(jsonObj.getString("supply_chain_goods_id"));
                        supplys.add(a);
                    }
//                    supply_chain_goods_id_list.add("]");

                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    String supply_str="";
                    Integer[] array = supplys.toArray(new Integer[supplys.size()]);
                    for (int i = 0 ; i < array.length ; i ++){
                        if (i==0){
                            supply_str=supply_str+array[i];
                        }else {
                            supply_str=supply_str+","+array[i];
                        }
                    }
                    queryJSObj.put("supply_chain_goods_id", supply_str);
                    queryJSObj.put("supply_chain_goods_settle_package_spec", supply_chain_goods_settle_package_spec);
                    queryJSObj.put("is_delete", 0);
                    queryJSObj.put("trade_date",trade_date);
                    String sql = createSelectSqlForPickupCompletionDetail(queryJSObj, query_offset, query_limit);
                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "pickup_completion_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForPickupCompletionDetail");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForPickupCompletionDetail");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForPickupCompletionDetail", "获取自提完工单明细失败"));
                        }
                    });
                }
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getRecordsForPickupCompletionDetail", "获取自提完工单明细失败")));
        }).
        onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForPickupCompletionDetail", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看自提完工单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForPickupCompletionDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("trade_date"), new CustomSql("pickup_completion_code"), new CustomSql("warehouse_id"),
        new CustomSql("buyer_name"), new CustomSql("buyer_id"), new CustomSql("order_code"), new CustomSql("list_goods_id"), new CustomSql("list_package_spec"), new CustomSql("sales_package_spec_id"),
        new CustomSql("order_number"), new CustomSql("order_weight"), new CustomSql("goods_batch_code"), new CustomSql("supply_chain_goods_id"),
                        new CustomSql("( select lg.list_goods_name " +
                                "from list_goods lg where lg.is_delete=0 and lg.id=list_goods_id ) as list_goods_name"),
                        new CustomSql("(select spst.package_spec_name from sales_package_spec spst where spst.is_delete=0 " +
                                "and spst.id=sales_package_spec_id ) as package_spec_name"),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "),
        new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("pickup_number"), new CustomSql("diff_number"), new CustomSql("pickup_weight"), new CustomSql("diff_weight"),
        new CustomSql("is_delete"),new CustomSql("supplier_id"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("pickup_completion_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看采购退货单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForPurchaseReturnDetail(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表purchase_return_detail的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String purchase_return_date = bodyJSObj.getString("purchase_return_date");
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detail 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();
        Set<String> supplier_id_list_set = new HashSet<String>();
        //首先根据聚合商品名获取对应的供应链商品名
        Set<Integer> supplys= new HashSet<>();
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                if (resJSArray1.size()>0){
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        Integer a = Integer.valueOf(jsonObj.getString("supply_chain_goods_id"));
                        supplys.add(a);
                    }

                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    String supply_str="";
                    Integer[] array = supplys.toArray(new Integer[supplys.size()]);
                    for (int i = 0 ; i < array.length ; i ++){
                        if (i==0){
                            supply_str=supply_str+array[i];
                        }else {
                            supply_str=supply_str+","+array[i];
                        }
                    }
                    queryJSObj.put("supply_chain_goods_id", supply_str);
                    queryJSObj.put("is_delete", 0);
                    queryJSObj.put("purchase_return_date",purchase_return_date);
                    String sql = createSelectSqlForPurchaseReturnDetail(queryJSObj, query_offset, query_limit);
                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "purchase_return_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForPurchaseReturnDetail");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForPurchaseReturnDetail");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForPurchaseReturnDetail", "获取采购退货单明细失败"));
                        }
                    });
                }else {
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getRecordsForPurchaseReturnDetail", "获取采购退货单明细失败")));
        }).
        onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForPurchaseReturnDetail", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看采购退货单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForPurchaseReturnDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("purchase_return_code"), new CustomSql("goods_batch_code"),
        new CustomSql("supply_chain_goods_id"),new CustomSql("purchase_return_date"),
                        new CustomSql("( select lg.supplier_name " +
                                "from supplier_info lg where lg.is_delete=0 and lg.id=supplier_id ) as supplier_name"),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "),
                        new CustomSql("supplier_id"), new CustomSql("purchase_return_weight"), new CustomSql("purchase_return_number"), new CustomSql("warehouse_id"),
        new CustomSql("(select w.warehouse_name from warehouse w  where w.is_delete=0  and w.id=warehouse_id ) as warehouse_name"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"), new CustomSql("supply_chain_goods_settle_package_spec"))
        .addCustomFromTable("purchase_return_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看期末明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForEndBatchDetial(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String time_line = bodyJSObj.getString("time_line");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;

        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 end_batch_detial 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> supplier_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();
        //首先根据聚合商品名获取对应的供应链商品名
        Set<Integer> supplys= new HashSet<>();
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先根据聚合商品名获取对应的供应链商品名
            JsonObject queryJSObj1 = new JsonObject();
            queryJSObj1.put("aggregation_id", aggregation_id);
            String get_supply_chain_gooods_id_sql = createSelectSqlGetSupplyChainGooodsId(queryJSObj1, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, get_supply_chain_gooods_id_sql, "getInitialBatchDetialRecords")
            .onSuccess(resJSArray1 -> {
                //        取出每条记录中含code字段的值放入对应的集合
                if (resJSArray1.size()==0){
                    JsonObject dataJSObj = new JsonObject();
                    dataJSObj.put("total", 0).put("records","");
                    responseJSObj.put("id", 0).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                }else {
                    for (int i = 0; i < resJSArray1.size(); i++) {
                        JsonObject jsonObj = resJSArray1.getJsonObject(i);
                        Integer a = Integer.valueOf(jsonObj.getString("supply_chain_goods_id"));
                        supplys.add(a);
                    }

                    //用于传递给构建sql的JsonObject
                    queryJSObj.put("warehouse_id", warehouse_id);
                    String supply_str="";
                    Integer[] array = supplys.toArray(new Integer[supplys.size()]);
                    for (int i = 0 ; i < array.length ; i ++){
                        if (i==0){
                            supply_str=supply_str+array[i];
                        }else {
                            supply_str=supply_str+","+array[i];
                        }
                    }
                    queryJSObj.put("supply_chain_goods_id", supply_str);
                    queryJSObj.put("supply_chain_goods_settle_package_spec", supply_chain_goods_settle_package_spec);
                    queryJSObj.put("is_delete", 0);
                    queryJSObj.put("time_line", time_line);
                    String sql = createSelectSqlForEndBatchDetial(queryJSObj, query_offset, query_limit);
                    //获取满足条件的记录总数
                    String count_sql = this.commonRepository.createCountSql(queryJSObj, "initial_batch_detail");
                    Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForEndBatchDetial");
                    Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForEndBatchDetial");
                    CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                        if (ar2.succeeded()) {
                            int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                            JsonObject dataJSObj = new JsonObject();
                            JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                            dataJSObj.put("total", total_records).put("records",recordsJSArray);
                            responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                            promise.complete(responseJSObj);
                        } else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForEndBatchDetial", "获取期末库存批次明细失败"));
                        }
                    });

                }
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getRecordsForEndBatchDetial", "获取期末库存批次明细失败")));
        }).
        onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForEndBatchDetial", "数据库连接失败")));
        return promise.future();
    }


    /**
     * 创建查询符合搜索条件记录的sql语句——查看期末明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForEndBatchDetial(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();

        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supply_chain_goods_id"),new CustomSql("time_line"),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "),new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("goods_batch_code"),
        new CustomSql("supplier_id"), new CustomSql("(select si.supplier_name from supplier_info si where si.is_delete=0 and si.id=supplier_id ) as supplier_name "),
                        new CustomSql("real_settlement_price"), new CustomSql("transport_price"), new CustomSql("land_price"), new CustomSql("inventory_land_acount"), new CustomSql("warehouse_id"),
        new CustomSql("(select w.warehouse_name from warehouse w where w.is_delete=0 and w.id=warehouse_id ) as warehouse_name "),
        new CustomSql("end_inventory_number"),new CustomSql("end_inventory_weight"),new CustomSql("end_inventory_amount"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("initial_batch_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }


    /**
     * 查看加工报损单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForGoodsProcessLoss(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_goods_process_loss的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String time_line = bodyJSObj.getString("time_line");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detail 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();

        queryJSObj.put("warehouse_id", warehouse_id);
        queryJSObj.put("aggregation_id", aggregation_id);
        queryJSObj.put("loss_date",time_line);
        queryJSObj.put("is_delete", 0);
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先获取供应商商品加工报损单
            String sql = createSelectSqlForSupplierGoodsProcessLossDetail(queryJSObj, query_offset, query_limit);
            String sql2 = createSelectSqlForSupplierGoodsProcessLossDetail2(queryJSObj, query_offset, query_limit);
            //获取满足条件的记录总数
            String count_sql = this.commonRepository.createCountSql(queryJSObj, "supplier_goods_process_loss");
            String count_sql2 = this.commonRepository.createCountSql(queryJSObj, "sales_supplier_goods_process_loss");
            Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForGoodsProcessLoss");
            Future<Integer> getTotalFuture2 = this.commonRepository.getRecordsCount(conn, count_sql2, "getRecordsForSalesGoodsProcessLoss");
            Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForGoodsProcessLoss");
            Future<JsonArray> future2 =  this.commonRepository.queryJsonArray(conn, sql2, "getRecordsForSalesGoodsProcessLoss");
            CompositeFuture.join(Arrays.asList(getTotalFuture, future ,getTotalFuture2,future2)).onComplete(ar2 -> {
                if (ar2.succeeded()) {
                    int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                    int total_records2 = Integer.valueOf(ar2.result().list().get(2).toString());
                    if (total_records!=0){
                        JsonObject dataJSObj = new JsonObject();
                        JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                        dataJSObj.put("total", total_records).put("records",recordsJSArray);
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }else if (total_records2!=0){
                        JsonObject dataJSObj = new JsonObject();
                        JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(3);
                        dataJSObj.put("total", total_records2).put("records",recordsJSArray);
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }else {
                        JsonObject dataJSObj = new JsonObject();
                        dataJSObj.put("total", 0).put("records","");
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }
                } else {
                    logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                    promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForGoodsProcessLoss", "获取供应商商品加工报损单失败"));
                }
            });
        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForGoodsProcessLoss", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看加工报损单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSupplierGoodsProcessLossDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("warehouse_id"), new CustomSql("supplier_goods_process_loss_code"), new CustomSql("partner_loss_ratio_id"),
        new CustomSql("(select plr.loss_type_name from partner_loss_ratio plr where plr.is_delete=0 " +
                "and plr.id=partner_loss_ratio_id ) as loss_type_name"),
        new CustomSql("(select spgiad.goods_batch_code " +
                "from supplier_pickup_goods_inspect_accept_detail spgiad " +
                "where spgiad.is_delete=0 " +
                "and spgiad.id=supplier_pickup_goods_inspect_accept_detail_id ) as goods_batch_code "),
        new CustomSql("(select w.warehouse_name from warehouse w where w.is_delete=0 and w.id=warehouse_id ) as warehouse_name "),
        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "), new CustomSql("supply_chain_goods_id"), new CustomSql("loss_weight"), new CustomSql("loss_number"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("supplier_goods_process_loss");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看加工报损单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSupplierGoodsProcessLossDetail2(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("warehouse_id"), new CustomSql("sales_supplier_goods_process_loss_code"), new CustomSql("partner_loss_ratio_id"),
        new CustomSql("(select plr.loss_type_name from partner_loss_ratio plr where plr.is_delete=0 and plr.id=partner_loss_ratio_id ) as loss_type_name"),
        new CustomSql("(select spgiad.goods_batch_code " +
                                "from sales_supplier_pickup_goods_inspect_accept_detail spgiad " +
                                "where spgiad.is_delete=0 " +
                                "and spgiad.id=sales_supplier_pickup_goods_inspect_accept_detail_id ) as goods_batch_code "),
        new CustomSql("(select w.warehouse_name from warehouse w where w.is_delete=0 and w.id=warehouse_id ) as warehouse_name "),
        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "), new CustomSql("supply_chain_goods_id"), new CustomSql("loss_weight"), new CustomSql("loss_number"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("sales_supplier_goods_process_loss");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看销售地区供应商商品加工报损单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSalesSupplierGoodsProcessLossDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("warehouse_id"), new CustomSql("supplier_goods_process_loss_code"), new CustomSql("loss_type_name"),
        new CustomSql("goods_batch_code"), new CustomSql("supply_chain_goods_id"), new CustomSql("loss_weight"), new CustomSql("loss_number"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("sales_supplier_goods_process_loss");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看盘盈盘亏单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForGoodsProfitLoss(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_goods_profit_loss的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String inspect_stock_date= bodyJSObj.getString("inspect_stock_date");
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detail 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();

        queryJSObj.put("warehouse_id", warehouse_id);
        queryJSObj.put("aggregation_id", aggregation_id);
        queryJSObj.put("is_delete", 0);
        queryJSObj.put("inspect_stock_date",inspect_stock_date);
        this.commonRepository.getCon(client).onSuccess(conn -> {
            //先获取供应商商品盘盈盘亏单
            String sql = createSelectSqlForSupplierGoodsProfitLossDetail(queryJSObj, query_offset, query_limit);
            String sql2 = createSelectSqlForSalesSupplierGoodsProfitLossDetail(queryJSObj, query_offset, query_limit);
            //获取满足条件的记录总数
            String count_sql = this.commonRepository.createCountSql(queryJSObj, "supplier_goods_profit_loss");
            String count_sql2 = this.commonRepository.createCountSql(queryJSObj, "sales_supplier_goods_profit_loss");
            Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "getRecordsForGoodsProfitLoss");
            Future<Integer> getTotalFuture2 = this.commonRepository.getRecordsCount(conn, count_sql2, "getRecordsForSalesGoodsProfitLoss");
            Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getRecordsForGoodsProfitLoss");
            Future<JsonArray> future2 =  this.commonRepository.queryJsonArray(conn, sql2, "getRecordsForSalesGoodsProfitLoss");
            CompositeFuture.join(Arrays.asList(getTotalFuture, future ,getTotalFuture2,future2)).onComplete(ar2 -> {
                if (ar2.succeeded()) {
                    int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                    int total_records2 = Integer.valueOf(ar2.result().list().get(2).toString());
                    if (total_records!=0){
                        JsonObject dataJSObj = new JsonObject();
                        JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);

                        for (int i = 0 ; i < recordsJSArray.size();i++){
                            JsonObject jsonObject =  recordsJSArray.getJsonObject(i);
                            double profit_loss_number = Double.parseDouble(jsonObject.getString("profit_loss_number"));
                            double real_settlement_package_spec = Double.parseDouble(jsonObject.getString("real_settlement_package_spec"));
                            BigDecimal bigDecimal1= new BigDecimal(profit_loss_number);
                            BigDecimal bigDecimal2= new BigDecimal(real_settlement_package_spec);
                            double weight = bigDecimal1.multiply(bigDecimal2).doubleValue();
                            jsonObject.put("all_weight",weight);

                        }
                        dataJSObj.put("total", total_records).put("records",recordsJSArray);
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }else if (total_records2!=0){
                        JsonObject dataJSObj = new JsonObject();
                        JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(3);
                        for (int i = 0 ; i < recordsJSArray.size();i++){
                            JsonObject jsonObject =  recordsJSArray.getJsonObject(i);
                            double profit_loss_number = Double.parseDouble(jsonObject.getString("profit_loss_number"));
                            double real_settlement_package_spec = Double.parseDouble(jsonObject.getString("real_settlement_package_spec"));
                            BigDecimal bigDecimal1= new BigDecimal(profit_loss_number);
                            BigDecimal bigDecimal2= new BigDecimal(real_settlement_package_spec);
                            double weight = bigDecimal1.multiply(bigDecimal2).doubleValue();
                            jsonObject.put("all_weight",weight);

                        }
                        dataJSObj.put("total", total_records2).put("records",recordsJSArray);
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }else {
                        JsonObject dataJSObj = new JsonObject();
                        dataJSObj.put("total", 0).put("records","");
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                        promise.complete(responseJSObj);
                    }
                } else {
                    logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                    promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsForGoodsProfitLoss", "获取盘盈盘亏单明细失败"));
                }
            });


        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsForGoodsProfitLoss", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看盘盈盘亏单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSupplierGoodsProfitLossDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supplier_goods_profit_loss_code"), new CustomSql("warehouse_id"),
                        new CustomSql("(select w.warehouse_name from warehouse w where w.is_delete=0 and w.id=warehouse_id ) as warehouse_name "),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "), new CustomSql("supply_chain_goods_id"), new CustomSql("(select spppd.real_settlement_package_spec " +
                                "from supplier_pickup_plan_payment_detail spppd " +
                                "where spppd.is_delete=0 " +
                                "and spppd.id =( " +
                                "    select spgiad.supplier_pickup_plan_payment_detail_id " +
                                "    from supplier_pickup_goods_inspect_accept_detail spgiad " +
                                "    where spgiad.is_delete=0 " +
                                "      and spgiad.id =supplier_pickup_goods_inspect_accept_detail_id " +
                                "    ) )as real_settlement_package_spec"), new CustomSql("profit_loss_number"),
                        new CustomSql("(select spgiad.goods_batch_code " +
                                "from supplier_pickup_goods_inspect_accept_detail spgiad " +
                                "where spgiad.is_delete=0 " +
                                "and spgiad.id=supplier_pickup_goods_inspect_accept_detail_id ) as goods_batch_code "),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("supplier_goods_profit_loss");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看销售地区供应商商品盘盈盘亏单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSalesSupplierGoodsProfitLossDetail(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supplier_goods_profit_loss_code"), new CustomSql("warehouse_id"),
        new CustomSql("(select w.warehouse_name from warehouse w where w.is_delete=0 and w.id=warehouse_id ) as warehouse_name "),
                        new CustomSql("(select scg.supply_chain_goods_name from supply_chain_goods scg  where scg.is_delete=0 " +
                                "and scg.id= supply_chain_goods_id ) as supply_chain_goods_name "), new CustomSql("supply_chain_goods_id"),
                        new CustomSql("(select spppd.real_settlement_package_spec " +
                                "from sales_pickup_plan_command spppd " +
                                "where spppd.is_delete=0 " +
                                "  and spppd.id =( " +
                                "    select spgiad.sales_pickup_plan_command_id " +
                                "    from sales_supplier_pickup_goods_inspect_accept_detail spgiad " +
                                "    where spgiad.is_delete=0 " +
                                "      and spgiad.id =sales_supplier_pickup_goods_inspect_accept_detail_id " +
                                ")) as real_settlement_package_spec"), new CustomSql("profit_loss_number"),
                        new CustomSql("(select spgiad.goods_batch_code " +
                                "from sales_supplier_pickup_goods_inspect_accept_detail spgiad " +
                                "where spgiad.is_delete=0 " +
                                "and spgiad.id=sales_supplier_pickup_goods_inspect_accept_detail_id ) as goods_batch_code "),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("sales_supplier_goods_profit_loss");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看供应商提货商品验收单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecordsForPickupGoodsInspectAccept(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("warehouse_id", "aggregation_id", "supply_chain_goods_settle_package_spec", "page_size", "page_index");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明\
        String warehouse_id = bodyJSObj.getString("warehouse_id");
        String aggregation_id = bodyJSObj.getString("aggregation_id");
        String supply_chain_goods_settle_package_spec = bodyJSObj.getString("supply_chain_goods_settle_package_spec");
        String supplier_pickup_goods_inspect_accept_id = bodyJSObj.getString("supplier_pickup_goods_inspect_accept_id");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;

        JsonObject queryJSObj = new JsonObject();

        //定义多个set，存储每一个 initial_batch_detial 中多个code
        Set<String> warehouse_id_list_set = new HashSet<String>();
        Set<String> list_goods_id_list_set = new HashSet<String>();
        Set<String> supply_chain_goods_id_list_set = new HashSet<String>();
        Set<String> sales_package_spec_type_id_list_set = new HashSet<String>();

        //首先根据聚合商品名获取对应的供应链商品名
        ArrayList<String> supply_chain_goods_id_list = new ArrayList<>();
//        supply_chain_goods_id_list.add("[");
        this.commonRepository.getCon(client).onSuccess(conn -> {
                    //先根据聚合商品名获取对应的供应链商品名
                    JsonObject queryJSObj1 = new JsonObject();
                    queryJSObj1.put("aggregation_id", aggregation_id);
            String sql ="SELECT ibd.id,ibd.supply_chain_goods_id, " +
                    "       (select a.supply_chain_goods_name " +
                    "        from supply_chain_goods a " +
                    "        where a.is_delete=0 " +
                    "        and  a.id=ibd.supply_chain_goods_id) as supply_chain_goods_name, " +
                    "       (select b.supplier_name " +
                    "        from supplier_info b " +
                    "        where b.is_delete=0 " +
                    "          and b.id=ibd.supplier_id) as supplier_name, " +
                    "       (select w.warehouse_name " +
                    "        from warehouse w " +
                    "        where w.is_delete=0 " +
                    "          and w.id=ibd.warehouse_id) as warehouse_name, " +
                    "       ibd.supply_chain_goods_settle_package_spec,ibd.goods_batch_code,ibd.supplier_id, " +
                    "       ibd.real_settlement_price, " +
                    "       ibd.transport_price,ibd.land_price,ibd.accept_number,ibd.accept_weight,ibd.supplier_pickup_goods_inspect_accept_id, " +
                    " (select a.supplier_pickup_goods_inspect_accept_code " +
                    " from supplier_pickup_goods_inspect_accept a " +
                    " where a.is_delete=0 " +
                    " and a.id=( " +
                    " select spgiad.supplier_pickup_goods_inspect_accept_id " +
                    " from supplier_pickup_goods_inspect_accept_detail spgiad " +
                    " where spgiad.is_delete=0 " +
                    " and spgiad.id =ibd.supplier_pickup_goods_inspect_accept_id  limit 1" +
                    "    ) )as supplier_pickup_goods_inspect_accept_code ," +
                    " sales_supplier_pickup_goods_inspect_accept_id,warehouse_id, " +
                    " (select a.supplier_pickup_goods_inspect_accept_code " +
                    " from sales_supplier_pickup_goods_inspect_accept a " +
                    " where a.is_delete=0 " +
                    "  and a.id=( " +
                    "    select spgiad.sales_supplier_pickup_goods_inspect_accept_id " +
                    "    from sales_supplier_pickup_goods_inspect_accept_detail spgiad " +
                    "    where spgiad.is_delete=0 " +
                    "      and spgiad.id =ibd.sales_supplier_pickup_goods_inspect_accept_id limit 1" +
                    ") ) as supplier_pickup_goods_inspect_accept_code2 ," +
                    "       ibd.is_delete,ibd.create_user, " +
                    "      ibd.update_user,ibd.create_time,ibd.update_time FROM initial_batch_detail ibd " +
                    "    WHERE ibd.is_delete=0 " +
                    "    and ibd.warehouse_id="+warehouse_id+" " +
                    "    and ibd.supply_chain_goods_settle_package_spec='"+supply_chain_goods_settle_package_spec+"' " +
                    "    and ibd.aggregation_id ="+aggregation_id+"  " +
                    "    and ibd.is_delete=0" +
                    "    order by ibd.id desc limit "+query_limit+" offset "+query_offset+" ";

            //获取满足条件的记录总数
            String count_sql = this.commonRepository.createCountSql(queryJSObj, "initial_batch_detail");
            Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "get_list_goods_batch_goods_psi");
            Future<JsonArray> future =  this.commonRepository.queryJsonArray(conn, sql, "getInitialBatchDetialRecords");
            CompositeFuture.join(Arrays.asList(getTotalFuture, future )).onComplete(ar2 -> {
                if (ar2.succeeded()) {
                    int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                    JsonObject dataJSObj = new JsonObject();
                    JsonArray recordsJSArray=(JsonArray)ar2.result().list().get(1);
                    dataJSObj.put("total", recordsJSArray.size()).put("records",recordsJSArray);
                    responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                    promise.complete(responseJSObj);
                } else {
                    logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                    promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getSupplierBatchGoodspsiRecords", "获取供应商批次商品进销存参数失败"));
                }
            });
                }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getSupplierBatchGoodspsiRecords", "数据库连接失败")));
        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看供应商提货商品验收单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSupplierPickupGoodsInspectAccept(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supply_chain_goods_id"), new CustomSql("supply_chain_goods_settle_package_spec"), new CustomSql("goods_batch_code"),
                        new CustomSql("supplier_id"), new CustomSql("real_settlement_price"), new CustomSql("transport_price"), new CustomSql("land_price"),
                        new CustomSql("inventory_number"),new CustomSql("  (select a.supply_chain_goods_name " +
                                "        from supply_chain_goods a " +
                                "        where a.is_delete=0 " +
                                "        and  a.id=supply_chain_goods_id) as supply_chain_goods_name "),
                        new CustomSql("     (select b.supplier_name " +
                                "        from supplier_info b " +
                                "        where b.is_delete=0 " +
                                "          and b.id=supplier_id) as supplier_name "),
                        new CustomSql("  (select w.warehouse_name " +
                                "        from warehouse w " +
                                "        where w.is_delete=0 " +
                                "          and w.id=warehouse_id) as warehouse_name "),
                        new CustomSql(""),
                        new CustomSql("inventory_weight"), new CustomSql("inventory_land_acount"), new CustomSql("warehouse_id"),
                        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
                .addCustomFromTable("initial_batch_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 创建查询符合搜索条件记录的sql语句——查看销售地区供应商商品供应商提货商品验收单明细
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSqlForSalesSupplierPickupGoodsInspectAccept(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("supplier_pickup_goods_inspect_accept_id"), new CustomSql("supply_chain_goods_id"), new CustomSql("goods_batch_code"),
        new CustomSql("total_weight"), new CustomSql("total_number"), new CustomSql("sales_pickup_plan_command_id"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("sales_supplier_pickup_goods_inspect_accept_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
// 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    private String createSelectSqlGetSupplyChainGooodsId(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("supply_chain_goods_id")).addCustomFromTable("goods_parameter");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }

    /**
     * 查看供应商提货商品验收单明细 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getUpdateForInitialBatchDetial(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传的数值字段
        List<String> numeric_fields = Arrays.asList("id", "inventory_number", "inventory_weight");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }

        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表supplier_batch_goods_psi的说明\
        String id = bodyJSObj.getString("id");
        String inventory_number = bodyJSObj.getString("inventory_number");
        String inventory_weight = bodyJSObj.getString("inventory_weight");
        this.commonRepository.getCon(client).onSuccess(conn -> {
                    //先根据聚合商品名获取对应的供应链商品名

                    String sql  = "update initial_batch_detail set inventory_number="+inventory_number+",inventory_weight="+inventory_weight+" where id="+id+" ";
                    this.commonRepository.queryJsonArray(conn, sql, "updateInitialBatchDetialRecords")
                            .onSuccess(resJSArray1 -> {
                                responseJSObj.put("code",200).put("msg", "更新成功!");
                                promise.complete(responseJSObj);
                            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "updateInitialBatchDetialRecords", "更新初期库存的数据失败")));
                }).
                onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "updateInitialBatchDetialRecords", "数据库连接失败")));
        return promise.future();
    }



    /**
     * 生成库存
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> generateInventory(PgPool client, JsonObject config, JsonObject bodyJSObj, User user) {
        long create_user2 = Long.parseLong(user.attributes().getJsonObject("accessToken").getString("username"));
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        //生成当天日期的字符串
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String a1 = String.valueOf(year);
        String a2="";
        if (month<10){
            a2 = "0"+String.valueOf(month);
        }else {
            a2 = String.valueOf(month);
        }
        String a3="";
        if (day<10){
            a3 = "0"+String.valueOf(day);
        }else {
            a3 = String.valueOf(day);
        }
        String date =a1+"-"+a2+"-"+a3;
        //往后推一天
        calendar.add(Calendar.DATE,1);
        int year1 = calendar.get(Calendar.YEAR);
        int month1 = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以要加1
        int day1 = calendar.get(Calendar.DAY_OF_MONTH);
        String a11 = String.valueOf(year1);
        String a21="";
        if (month1<10){
            a21 = "0"+String.valueOf(month1);
        }else {
            a21 = String.valueOf(month1);
        }
        String a31="";
        if (day1<10){
            a31 = "0"+String.valueOf(day1);
        }else {
            a31 = String.valueOf(day1);
        }
        String date2 =a11+"-"+a21+"-"+a31;
        this.commonRepository.getCon(client).onSuccess(conn -> {
                    String supplier_sql = "select spgiad.total_number, spgiad.id, " +
                            "       (select sgpl.loss_weight " +
                            "        from supplier_goods_process_loss sgpl " +
                            "        where sgpl.is_delete=0 " +
                            "          and sgpl.supplier_pickup_goods_inspect_accept_detail_id=spgiad.id) as loss_weight, " +
                            "       (select sgpl.loss_number " +
                            "        from supplier_goods_process_loss sgpl " +
                            "        where sgpl.is_delete=0 " +
                            "          and sgpl.supplier_pickup_goods_inspect_accept_detail_id=spgiad.id) as loss_number, " +
                            "        (select sgpl.profit_loss_number " +
                            "         from supplier_goods_profit_loss sgpl " +
                            "         where sgpl.is_delete=0 " +
                            "           and sgpl.supplier_pickup_goods_inspect_accept_detail_id=spgiad.id) as profit_loss_number, " +
                            "        (select sgpl.profit_loss_weight " +
                            "         from supplier_goods_profit_loss sgpl " +
                            "         where sgpl.is_delete=0 " +
                            "           and sgpl.supplier_pickup_goods_inspect_accept_detail_id=spgiad.id) as profit_loss_weight, " +
                            "       (select spppd.real_settlement_package_spec " +
                            "        from supplier_pickup_plan_payment_detail spppd " +
                            "        where spppd.is_delete=0 " +
                            "          and spppd.id =spgiad.supplier_pickup_plan_payment_detail_id  )as real_settlement_package_spec, " +
                            "       spgiad.aggregation_id, " +
                            "       spgiad.supply_chain_goods_id, " +
                            " (select scg.class_lv1_id from supply_chain_goods scg where scg.is_delete=0 and scg.id=spgiad.supply_chain_goods_id) as class_lv1_id, "+
                            " (select scg.class_lv2_id from supply_chain_goods scg  where scg.is_delete=0 and scg.id=spgiad.supply_chain_goods_id) as class_lv2_id, "+
                            " (select scg.variety_id from supply_chain_goods scg  where scg.is_delete=0 and scg.id=spgiad.supply_chain_goods_id) as variety_id, "+
                            "       spgiad.goods_batch_code, " +
                            "       (select sp.warehouse_id " +
                            "        from supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id) as warehouse_id, " +
                            " (select w.big_area_id from warehouse w  where  w.is_delete=0 and w.id=( " +
                            "    select sp.warehouse_id from supplier_pickup_goods_inspect_accept sp  where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id " +
                            "    )) as big_area_id, " +
                            " (select w.site_id from warehouse w  where  w.is_delete=0 and w.id=( " +
                            "    select sp.warehouse_id from supplier_pickup_goods_inspect_accept sp  where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id " +
                            "    )) as site_id, " +
                            "       (select sp.supplier_id  from supplier_pickup_goods_inspect_accept sp  where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id) as supplier_id, " +
                            " (select scp.partner_name from supply_chain_partner scp where scp.is_delete=0 " +
                            "                and scp.id = (select si.partner_id from supplier_info si where si.is_delete=0 and si.id=( " +
                            "        select sp.supplier_id  from supplier_pickup_goods_inspect_accept sp  where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id " +
                            "        ))) as partner_name," +
                            " (select rppna.gross_profit_commission_processing_center_manager  from real_pickup_plan_number_allocation rppna  where rppna.is_delete=0  and rppna.id=spgiad.real_pickup_plan_number_allocation_id ) as gross_profit_commission_processing_center_manager,"+
                            "       (select sp.goods_gather_area_id " +
                            "        from supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id ) as goods_gather_area_id, " +
                            " ( select ppppb.cif_gross_profit_margin " +
                            "from prepare_pickup_plan_price_bid ppppb " +
                            "where ppppb.is_delete=0 " +
                            "and ppppb.id=spgiad.prepare_pickup_plan_price_bid_id ) as cif_gross_profit_margin, "+
//                            " (select scg.class_lv1_id " +
//                            "from supply_chain_goods scg " +
//                            "where scg.is_delete=0 " +
//                            "and scg.id=spgiad.supply_chain_goods_id ) as class_lv1_id, "+
                            " ( select gpscg.supply_chain_goods_weight_package_spec " +
                            " from goods_parameter_supply_chain_goods gpscg " +
                            " where gpscg.is_delete=0 " +
                            " and gpscg.id =spgiad.goods_parameter_supply_chain_goods_id ) as supply_chain_goods_weight_package_spec, "+
                            " (select si.partner_id   from supplier_info si   where si.is_delete=0 " +
                            " and si.id=( select sp.supplier_id  from supplier_pickup_goods_inspect_accept sp  where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id ) ) as partner_id ,"+
                            "       (select sp.supplier_pickup_goods_inspect_accept_code " +
                            "        from supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=spgiad.supplier_pickup_goods_inspect_accept_id) as supplier_pickup_goods_inspect_accept_code " +
                            "from supplier_pickup_goods_inspect_accept_detail spgiad " +
                            "where spgiad.is_delete=0 " +
                            "and spgiad.supplier_pickup_goods_inspect_accept_id in ( " +
                            "    select id " +
                            "    from supplier_pickup_goods_inspect_accept " +
                            "    where is_delete=0 " +
                            "      and arrival_date ='"+date+"' " +
                            "    )";
                    Future<JsonArray> future1 =  this.commonRepository.queryJsonArray(conn, supplier_sql, "getRecordsSupplier");
                    String sales_sql = "select sspgiad.total_number, sspgiad.id, " +
                            "       (select ssgpl.loss_weight " +
                            "        from sales_supplier_goods_process_loss ssgpl " +
                            "        where ssgpl.is_delete=0 " +
                            "          and ssgpl.sales_supplier_pickup_goods_inspect_accept_detail_id=sspgiad.id) as loss_weight, " +
                            "       (select ssgpl.loss_number " +
                            "        from sales_supplier_goods_process_loss ssgpl " +
                            "        where ssgpl.is_delete=0 " +
                            "          and ssgpl.sales_supplier_pickup_goods_inspect_accept_detail_id=sspgiad.id) as loss_number, " +
                            "       (select ssgpl2.profit_loss_number " +
                            "        from sales_supplier_goods_profit_loss ssgpl2 " +
                            "        where ssgpl2.is_delete=0 " +
                            "          and ssgpl2.sales_supplier_pickup_goods_inspect_accept_detail_id=sspgiad.id) as profit_loss_number, " +
                            "       (select ssgpl2.profit_loss_weight " +
                            "        from sales_supplier_goods_profit_loss ssgpl2 " +
                            "        where ssgpl2.is_delete=0 " +
                            "          and ssgpl2.sales_supplier_pickup_goods_inspect_accept_detail_id=sspgiad.id) as profit_loss_weight, " +
                            "       (select sppc.real_settlement_package_spec " +
                            "        from sales_pickup_plan_command sppc " +
                            "        where sppc.is_delete=0 " +
                            "          and sppc.id =sspgiad.sales_pickup_plan_command_id  )as real_settlement_package_spec, " +
                            "       sspgiad.aggregation_id, " +
                            " (select scg.class_lv1_id from supply_chain_goods scg where scg.is_delete=0 and scg.id=sspgiad.supply_chain_goods_id) as class_lv1_id, "+
                            " (select scg.class_lv2_id from supply_chain_goods scg  where scg.is_delete=0 and scg.id=sspgiad.supply_chain_goods_id) as class_lv2_id, "+
                            " (select scg.variety_id from supply_chain_goods scg  where scg.is_delete=0 and scg.id=sspgiad.supply_chain_goods_id) as variety_id, "+
                            "       sspgiad.supply_chain_goods_id, " +
                            "       sspgiad.goods_batch_code, " +
                            "       (select sp.warehouse_id " +
                            "        from sales_supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) as warehouse_id, " +
                            " (select w.big_area_id from warehouse w  where  w.is_delete=0 and w.id=( " +
                            "    (select sp.warehouse_id  from sales_supplier_pickup_goods_inspect_accept sp  where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) " +
                            "    ) ) as big_area_id,  " +
                            " (select w.site_id from warehouse w  where  w.is_delete=0 and w.id=( " +
                            "    (select sp.warehouse_id  from sales_supplier_pickup_goods_inspect_accept sp  where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) " +
                            "    ) ) as site_id,  " +
                            "       (select sp.supplier_id " +
                            "        from sales_supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) as supplier_id, " +
                            " ( select scp.partner_name from supply_chain_partner scp where scp.is_delete=0 " +
                            "                and scp.id = (select si.partner_id from supplier_info si where si.is_delete=0 and si.id=( " +
                            "        select sp.supplier_id from sales_supplier_pickup_goods_inspect_accept sp  where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id " +
                            "        )) ) as partner_name, " +
                            "       (select sp.goods_gather_area_id " +
                            "        from sales_supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) as goods_gather_area_id, " +
//                            " (select scg.class_lv1_id " +
//                            "from supply_chain_goods scg " +
//                            "where scg.is_delete=0 " +
//                            "and scg.id=sspgiad.supply_chain_goods_id ) as class_lv1_id, "+
                            " ( select gpscg.supply_chain_goods_weight_package_spec " +
                            " from goods_parameter_supply_chain_goods gpscg " +
                            " where gpscg.is_delete=0 " +
                            " and gpscg.id =sspgiad.goods_parameter_supply_chain_goods_id ) as supply_chain_goods_weight_package_spec, "+
                            " ( select lp.member_price1  from list_price lp  where lp.is_delete=0 " +
                            " and lp.id = (  select sppc.platform_list_id  from sales_pickup_plan_command sppc  where sppc.is_delete=0 " +
                            "  and sppc.id=sspgiad.sales_pickup_plan_command_id  )) as member_price1, "+
                            " ( select lp.base_price  from list_price lp  where lp.is_delete=0 " +
                            " and lp.id = (  select sppc.platform_list_id  from sales_pickup_plan_command sppc  where sppc.is_delete=0 " +
                            "  and sppc.id=sspgiad.sales_pickup_plan_command_id  )) as base_price, "+
                            " ( select lp.normal_price1  from list_price lp  where lp.is_delete=0 " +
                            " and lp.id = (  select sppc.platform_list_id  from sales_pickup_plan_command sppc  where sppc.is_delete=0 " +
                            "  and sppc.id=sspgiad.sales_pickup_plan_command_id  )) as normal_price1, "+
                            "  ( select sppc.real_settlement_price " +
                            "from sales_pickup_plan_command sppc " +
                            "where sppc.is_delete=0 " +
                            "  and sppc.id=sspgiad.sales_pickup_plan_command_id ) as real_settlement_price, "+
                            "  ( select sppc.platform_list_mark " +
                            "from sales_pickup_plan_command sppc " +
                            "where sppc.is_delete=0 " +
                            "  and sppc.id=sspgiad.sales_pickup_plan_command_id ) as platform_list_mark, "+
                            " (select si.partner_id   from supplier_info si   where si.is_delete=0 " +
                            " and si.id=( select sp.supplier_id  from sales_supplier_pickup_goods_inspect_accept sp  where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) ) as partner_id ,"+
                            "       (select sp.supplier_pickup_goods_inspect_accept_code " +
                            "        from sales_supplier_pickup_goods_inspect_accept sp " +
                            "        where sp.id=sspgiad.sales_supplier_pickup_goods_inspect_accept_id ) as supplier_pickup_goods_inspect_accept_code " +
                            "from sales_supplier_pickup_goods_inspect_accept_detail sspgiad " +
                            "where sspgiad.is_delete=0 " +
                            "  and sspgiad.sales_supplier_pickup_goods_inspect_accept_id in ( " +
                            "    select id " +
                            "    from sales_supplier_pickup_goods_inspect_accept " +
                            "    where is_delete=0 " +
                            "      and arrival_date ='"+date+"' " +
                            ")";
                    Future<JsonArray> future2 =  this.commonRepository.queryJsonArray(conn, sales_sql, "getRecordsSalesSupplier");
                    CompositeFuture.join(Arrays.asList(future1, future2 )).onComplete(ar2 -> {
                        if (ar2.succeeded()){
                            JsonArray recordsJSArray1=(JsonArray)ar2.result().list().get(0);
                            JsonArray recordsJSArray2=(JsonArray)ar2.result().list().get(1);
                            List<InitialBatchDetailVo> voList =new ArrayList<>();
                            if (recordsJSArray1.size()>0 || recordsJSArray2.size()>0){
                                if (recordsJSArray1.size()>0){
                                    //聚集区有数据
                                    for (int i = 0 ;i < recordsJSArray1.size();i++){
                                        JsonObject jsonObject =   recordsJSArray1.getJsonObject(i);
                                        InitialBatchDetailVo vo = new InitialBatchDetailVo();
                                        vo.setId(Integer.valueOf(jsonObject.getString("id")));
                                        vo.setTotal_number(Integer.valueOf(jsonObject.getString("total_number")==null? "0":jsonObject.getString("total_number")));
                                        vo.setLoss_number(Integer.valueOf(jsonObject.getString("loss_number")==null? "0":jsonObject.getString("loss_number")));
                                        vo.setProfit_loss_number(Integer.valueOf(jsonObject.getString("profit_loss_number")==null? "0":jsonObject.getString("profit_loss_number")));
                                        vo.setLoss_weight(Double.parseDouble(jsonObject.getString("loss_weight")==null? "0":jsonObject.getString("loss_weight")));
                                        vo.setAggregation_id(Integer.valueOf(jsonObject.getString("aggregation_id")));
                                        vo.setSupply_chain_goods_id(Integer.valueOf(jsonObject.getString("supply_chain_goods_id")));
                                        vo.setWarehouse_id(Integer.valueOf(jsonObject.getString("warehouse_id")));
                                        vo.setSupplier_id(Integer.valueOf(jsonObject.getString("supplier_id")));
                                        vo.setGoods_batch_code(jsonObject.getString("goods_batch_code"));
                                        vo.setClass_lv1_id(Integer.valueOf(jsonObject.getString("class_lv1_id")));
                                        vo.setClass_lv2_id(Integer.valueOf(jsonObject.getString("class_lv2_id")));
                                        vo.setVariety_id(Integer.valueOf(jsonObject.getString("variety_id")));
                                        vo.setSite_id(Integer.valueOf(jsonObject.getString("site_id")));
                                        vo.setBig_area_id(Integer.valueOf(jsonObject.getString("big_area_id")));
                                        vo.setGoods_gather_area_id(Integer.valueOf(jsonObject.getString("goods_gather_area_id")));
                                        vo.setPartner_id(Integer.valueOf(jsonObject.getString("partner_id")));
                                        vo.setReal_settlement_package_spec(Double.parseDouble(jsonObject.getString("real_settlement_package_spec")==null? "0":jsonObject.getString("real_settlement_package_spec")));
                                        vo.setSupplier_pickup_goods_inspect_accept_code(jsonObject.getString("supplier_pickup_goods_inspect_accept_code"));
                                        vo.setCif_gross_profit_margin(Double.parseDouble(jsonObject.getString("cif_gross_profit_margin")==null? "0":jsonObject.getString("cif_gross_profit_margin")));
                                        vo.setSupply_chain_goods_weight_package_spec(Double.parseDouble(jsonObject.getString("supply_chain_goods_weight_package_spec")==null? "0":jsonObject.getString("supply_chain_goods_weight_package_spec")));
                                        vo.setPartner_name(jsonObject.getString("partner_name"));
                                        vo.setGross_profit_commission_processing_center_manager(jsonObject.getString("gross_profit_commission_processing_center_manager"));
                                        BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                        BigDecimal bigDecimal2 =new BigDecimal(vo.getTotal_number());
                                        BigDecimal bigDecimal3 =new BigDecimal(vo.getProfit_loss_number());
                                        vo.setTotal_weight(bigDecimal1.multiply(bigDecimal2).doubleValue());
                                        vo.setProfit_loss_weight(Double.parseDouble(jsonObject.getString("profit_loss_weight")==null? "0":jsonObject.getString("profit_loss_weight")));
                                        vo.setType(1);
                                        voList.add(vo);
                                    }
                                }
                                //销售区有数据
                                for (int i = 0 ;i < recordsJSArray2.size();i++){
                                    JsonObject jsonObject =   recordsJSArray2.getJsonObject(i);
                                    InitialBatchDetailVo vo = new InitialBatchDetailVo();
                                    vo.setSaleId(Integer.valueOf(jsonObject.getString("id")));
                                    vo.setTotal_number(Integer.valueOf(jsonObject.getString("total_number")==null? "0":jsonObject.getString("total_number")));
                                    vo.setLoss_number(Integer.valueOf(jsonObject.getString("loss_number")==null? "0":jsonObject.getString("loss_number")));
                                    vo.setProfit_loss_number(Integer.valueOf(jsonObject.getString("profit_loss_number")==null? "0":jsonObject.getString("profit_loss_number")));
                                    vo.setLoss_weight(Double.parseDouble(jsonObject.getString("loss_weight")==null? "0":jsonObject.getString("loss_weight")));
                                    vo.setAggregation_id(Integer.valueOf(jsonObject.getString("aggregation_id")));
                                    vo.setSupply_chain_goods_id(Integer.valueOf(jsonObject.getString("supply_chain_goods_id")));
                                    vo.setWarehouse_id(Integer.valueOf(jsonObject.getString("warehouse_id")));
                                    vo.setSupplier_id(Integer.valueOf(jsonObject.getString("supplier_id")));
                                    vo.setGoods_batch_code(jsonObject.getString("goods_batch_code"));
                                    vo.setClass_lv1_id(Integer.valueOf(jsonObject.getString("class_lv1_id")));
                                    vo.setClass_lv2_id(Integer.valueOf(jsonObject.getString("class_lv2_id")));
                                    vo.setVariety_id(Integer.valueOf(jsonObject.getString("variety_id")));
                                    vo.setSite_id(Integer.valueOf(jsonObject.getString("site_id")));
                                    vo.setBig_area_id(Integer.valueOf(jsonObject.getString("big_area_id")));
                                    vo.setGoods_gather_area_id(Integer.valueOf(jsonObject.getString("goods_gather_area_id")));
                                    vo.setPartner_id(Integer.valueOf(jsonObject.getString("partner_id")));
                                    vo.setReal_settlement_package_spec(Double.parseDouble(jsonObject.getString("real_settlement_package_spec")));
                                    vo.setSupplier_pickup_goods_inspect_accept_code(jsonObject.getString("supplier_pickup_goods_inspect_accept_code"));
                                    vo.setPartner_name(jsonObject.getString("partner_name"));
                                    vo.setGross_profit_commission_processing_center_manager("");
                                    BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                    BigDecimal bigDecimal2 =new BigDecimal(vo.getTotal_number());
                                    BigDecimal bigDecimal3 =new BigDecimal(vo.getProfit_loss_number());
                                    vo.setTotal_weight(bigDecimal1.multiply(bigDecimal2).doubleValue());
                                    vo.setProfit_loss_weight(Double.parseDouble(jsonObject.getString("profit_loss_weight")==null? "0":jsonObject.getString("profit_loss_weight")));
                                    vo.setSupply_chain_goods_weight_package_spec(Double.parseDouble(jsonObject.getString("supply_chain_goods_weight_package_spec")==null? "0":jsonObject.getString("supply_chain_goods_weight_package_spec")));
                                    vo.setPlatform_list_mark(Integer.valueOf(jsonObject.getString("platform_list_mark")==null? "1":jsonObject.getString("platform_list_mark")));
                                    vo.setMember_price1(Double.parseDouble(jsonObject.getString("member_price1")==null? "0":jsonObject.getString("member_price1")));
                                    vo.setBase_price(Double.parseDouble(jsonObject.getString("base_price")==null? "0":jsonObject.getString("base_price")));
                                    vo.setNormal_price1(Double.parseDouble(jsonObject.getString("normal_price1")==null? "0":jsonObject.getString("normal_price1")));
                                    vo.setReal_settlement_price(Double.parseDouble(jsonObject.getString("real_settlement_price")==null? "0":jsonObject.getString("real_settlement_price")));
                                    if (vo.getPlatform_list_mark()==0){
                                        //不存在则默认0
                                        vo.setCif_gross_profit_margin(0.00);
                                    }else {
                                        //存在则
                                        double a=0.00;
                                        if (vo.getPlatform_list_mark()==1){
                                            a = vo.getBase_price();
                                        }else if(vo.getPlatform_list_mark()==2){
                                            a = vo.getMember_price1();
                                        }else if(vo.getPlatform_list_mark()==3){
                                            a = vo.getNormal_price1();
                                        }
                                        double real_settlement_price= vo.getReal_settlement_price();
                                        BigDecimal bigDecimal001=new BigDecimal(a);
                                        BigDecimal bigDecimal002=new BigDecimal(real_settlement_price);
                                        BigDecimal bigDecimal003 = bigDecimal001.subtract(bigDecimal002);
                                        vo.setCif_gross_profit_margin(bigDecimal003.divide(bigDecimal001,4, RoundingMode.DOWN).doubleValue());
                                    }
                                    vo.setType(2);
                                    voList.add(vo);
                                }
                                LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                String warehouse_ids="";
                                String supply_chain_goods_ids="";
                                String real_settlement_package_specs="";
                                String goods_batch_codes="";
                                String supplier_ids="";
                                String aggregation_ids="";
                                String supplier_pickup_goods_inspect_accept_codes="";
                                for (int y = 0 ; y < voList.size() ; y++){
                                    if (y==voList.size()-1){
                                        warehouse_ids=warehouse_ids+voList.get(y).getWarehouse_id();
                                        supply_chain_goods_ids=supply_chain_goods_ids+voList.get(y).getSupply_chain_goods_id();
                                        supplier_ids=supplier_ids+voList.get(y).getSupplier_id();
                                        real_settlement_package_specs=real_settlement_package_specs+voList.get(y).getReal_settlement_package_spec();
                                        goods_batch_codes=goods_batch_codes+"'"+voList.get(y).getGoods_batch_code()+"'";
                                        aggregation_ids=aggregation_ids+voList.get(y).getAggregation_id();
                                        supplier_pickup_goods_inspect_accept_codes=supplier_pickup_goods_inspect_accept_codes+"'"+voList.get(y).getSupplier_pickup_goods_inspect_accept_code()+"'";
                                    }else {
                                        warehouse_ids=warehouse_ids+voList.get(y).getWarehouse_id()+",";
                                        supply_chain_goods_ids=supply_chain_goods_ids+voList.get(y).getSupply_chain_goods_id()+",";
                                        supplier_ids=supplier_ids+voList.get(y).getSupplier_id()+",";
                                        real_settlement_package_specs=real_settlement_package_specs+voList.get(y).getReal_settlement_package_spec()+",";
                                        goods_batch_codes=goods_batch_codes+"'"+voList.get(y).getGoods_batch_code()+"',";
                                        aggregation_ids=aggregation_ids+voList.get(y).getAggregation_id()+",";
                                        supplier_pickup_goods_inspect_accept_codes=supplier_pickup_goods_inspect_accept_codes+"'"+voList.get(y).getSupplier_pickup_goods_inspect_accept_code()+"',";
                                    }
                                }
                                String select_sql="select id,warehouse_id,supplier_id,supply_chain_goods_id,goods_batch_code,supply_chain_goods_settle_package_spec,inventory_number,inventory_weight " +
                                        "from initial_batch_detail " +
                                        "where is_delete=0  "+
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supplier_id in ("+supplier_ids+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and goods_batch_code in ("+goods_batch_codes+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and time_line ='"+date+"' ";
                                Future<JsonArray> future3 =  this.commonRepository.queryJsonArray(conn, select_sql, "getSelect_sql");

                                String select_sql2 ="select warehouse_id,aggregation_id,supply_chain_goods_settle_package_spec " +
                                        "from supplier_batch_goods_psi " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and aggregation_id in ("+aggregation_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and time_line ='"+date+"'  ";
                                Future<JsonArray> future4 =  this.commonRepository.queryJsonArray(conn, select_sql2, "getSelect_sql2");

                                String select_sql3 ="select warehouse_id,aggregation_id,supply_chain_goods_settle_package_spec,goods_batch_code " +
                                        "from supplier_batch_goods_cost_price " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and aggregation_id in ("+aggregation_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and time_line ='"+date+"'  " +
                                        " and goods_batch_code in ("+goods_batch_codes+") ";
                                Future<JsonArray> future5 =  this.commonRepository.queryJsonArray(conn, select_sql3, "select_sql3");

                                String select_sql4 ="select warehouse_id,supply_chain_goods_id,supply_chain_goods_settle_package_spec,supplier_pickup_goods_inspect_accept_code, supplier_id " +
                                        "from goods_gross_profit_commission_detail " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and supplier_pickup_goods_inspect_accept_code in ("+supplier_pickup_goods_inspect_accept_codes+") " +
                                        "and time_line ='"+date+"'  " +
                                        " and supplier_id in ("+supplier_ids+") ";
                                Future<JsonArray> future6 =  this.commonRepository.queryJsonArray(conn, select_sql4, "select_sql3");



                                //判断已经存在的销售退货入库的数据 进行计算期末库存重量、件数
                                String select_sql6 ="select warehouse_id,supplier_id,goods_batch_codes,supply_chain_goods_id,supply_chain_goods_settle_package_spec,retrun_warehouse_number, " +
                                        "retrun_warehouse_weight " +
                                        "from sales_return_warehouse_detail " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supplier_id in ("+supplier_ids+") " +
                                        "and goods_batch_code in ("+goods_batch_codes+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and delivery_date ='"+date+"'  ";
                                Future<JsonArray> future8 =  this.commonRepository.queryJsonArray(conn, select_sql6, "select_sql6");

                                //判断已经存在 车次配送的数据 进行计算期末库存重量、件数
                                String select_sql7 ="select warehouse_id,supplier_id,goods_batch_codes,supply_chain_goods_id,supply_chain_goods_settle_package_spec," +
                                        " shift_delivery_plan_completion_number,shift_delivery_plan_completion_weight " +
                                        "from shift_delivery_plan_completion_detail " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supplier_id in ("+supplier_ids+") " +
                                        "and goods_batch_code in ("+goods_batch_codes+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and delivery_date ='"+date+"'  ";
                                Future<JsonArray> future9 =  this.commonRepository.queryJsonArray(conn, select_sql7, "select_sql7");

                                //判断已经存在 自提完工的数据 进行计算期末库存重量、件数
                                String select_sql8 ="select warehouse_id,supplier_id,goods_batch_codes,supply_chain_goods_id,supply_chain_goods_settle_package_spec, " +
                                        " pickup_number,pickup_weight " +
                                        "from pickup_completion_detail " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supplier_id in ("+supplier_ids+") " +
                                        "and goods_batch_code in ("+goods_batch_codes+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and trade_date ='"+date+"'  ";
                                Future<JsonArray> future10 =  this.commonRepository.queryJsonArray(conn, select_sql8, "select_sql8");

                                //判断已经存在 采购退货的数据 进行计算期末库存重量、件数
                                String select_sql13 ="select warehouse_id,supplier_id,goods_batch_codes,supply_chain_goods_id,supply_chain_goods_settle_package_spec, " +
                                        " purchase_return_number,purchase_return_weight " +
                                        "from purchase_return_detail " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and supplier_id in ("+supplier_ids+") " +
                                        "and goods_batch_code in ("+goods_batch_codes+") " +
                                        "and supply_chain_goods_id in ("+supply_chain_goods_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and purchase_return_date ='"+date+"'  ";
                                Future<JsonArray> future15 =  this.commonRepository.queryJsonArray(conn, select_sql13, "select_sql13");

                                //判断进销存数据 明天的数据是否存在 存在不做处理  不存在则需要新增
                                String select_sql14 ="select warehouse_id,aggregation_id,supply_chain_goods_settle_package_spec " +
                                        "from supplier_batch_goods_psi " +
                                        "where is_delete=0 " +
                                        "and warehouse_id in ("+warehouse_ids+") " +
                                        "and aggregation_id in ("+aggregation_ids+") " +
                                        "and supply_chain_goods_settle_package_spec in ("+real_settlement_package_specs+") " +
                                        "and time_line ='"+date2+"'  ";
                                Future<JsonArray> future16 =  this.commonRepository.queryJsonArray(conn, select_sql14, "select_sql14");

                                CompositeFuture.join(Arrays.asList(future3, future4,future5,future6,future8,future9,future10,future15,future16 )).onComplete(ar3 -> {
                                    if (ar3.succeeded()){
                                        JsonArray recordsJSArray3=(JsonArray)ar3.result().list().get(0);
                                        JsonArray recordsJSArray4=(JsonArray)ar3.result().list().get(1);
                                        JsonArray recordsJSArray5=(JsonArray)ar3.result().list().get(2);
                                        JsonArray recordsJSArray6=(JsonArray)ar3.result().list().get(3);

                                        JsonArray recordsJSArray8=(JsonArray)ar3.result().list().get(4);
                                        JsonArray recordsJSArray9=(JsonArray)ar3.result().list().get(5);
                                        JsonArray recordsJSArray10=(JsonArray)ar3.result().list().get(6);

                                        JsonArray recordsJSArray15=(JsonArray)ar3.result().list().get(7);
                                        JsonArray recordsJSArray16=(JsonArray)ar3.result().list().get(8);
                                        List<InitialBatchDetailVo> insertVo = new ArrayList<>();
                                        LinkedList<InitialBatchDetailVo> updateVo = new LinkedList<>();
                                        LinkedList<Integer> tomorrowInitialBatchDetail = new LinkedList<>();  //updateVo的数据 长度、顺序和tomorrowInitialBatchDetail的长度顺序一样

                                        List<InitialBatchDetailVo> insertVo2 = new ArrayList<>();
                                        List<InitialBatchDetailVo> insertVo2Tomorrow = new ArrayList<>(); //当天库存存在时候 需要新增明天的库存数据
                                        List<InitialBatchDetailVo> insertVo3= new ArrayList<>();
                                        List<InitialBatchDetailVo> insertVo4= new ArrayList<>();
                                        if (recordsJSArray3.size()>0){
                                            //存在已经生成的当日初期库存明细数据 则需要更新
                                            for (int r = 0 ; r<voList.size();r++){
                                                boolean need= false;
                                                for (int i = 0 ; i< recordsJSArray3.size();i++){
                                                    JsonObject jsonObject =   recordsJSArray3.getJsonObject(i);
                                                    Integer warehouse_id21 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    Integer supplier_id21 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    Integer supply_chain_goods_id21 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    String goods_batch_code21 = jsonObject.getString("goods_batch_code");
                                                    double supply_chain_goods_settle_package_spec= Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec")==null? "0":jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    double inventory_number= Double.parseDouble(jsonObject.getString("inventory_number")==null? "0":jsonObject.getString("inventory_number"));
//                                                    int inventory_number2 =(int) Math.floor(inventory_number);
//                                                    double inventory_weight= Double.parseDouble(jsonObject.getString("inventory_weight")==null? "0":jsonObject.getString("inventory_weight"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(supply_chain_goods_settle_package_spec);
                                                    BigDecimal bigDecimal2 =new BigDecimal(voList.get(r).getReal_settlement_package_spec());

                                                    if (warehouse_id21==voList.get(r).getWarehouse_id() && supplier_id21==voList.get(r).getSupplier_id()
                                                    && supply_chain_goods_id21==voList.get(r).getSupply_chain_goods_id() && goods_batch_code21.equals(voList.get(r).getGoods_batch_code())
                                                    && bigDecimal1.compareTo(bigDecimal2)==0 ){
                                                        //需要更新的数据
                                                        InitialBatchDetailVo voa = voList.get(r);
                                                        voa.setInitialBatchDetaiId(Integer.valueOf(jsonObject.getString("id")));
                                                        updateVo.add(voa);
                                                        need=true;
                                                        break;
                                                    }
                                                }
                                                if (!need){
                                                    //需要新增的数据
                                                    insertVo.add(voList.get(r));
                                                }
                                            }
                                        }else {
                                            //没有存在的库存明细直接新增
                                            for (InitialBatchDetailVo vo : voList){
                                                insertVo.add(vo);
                                            }
                                        }
                                        //存在已经生成的库存头数据 则过滤
                                        if (recordsJSArray4.size()>0){
                                            for (int r = 0 ; r<voList.size();r++){
                                                boolean need= false;
                                                for (int i = 0 ; i< recordsJSArray4.size();i++){
                                                    JsonObject jsonObject =   recordsJSArray4.getJsonObject(i);
                                                    Integer warehouse_id21 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    Integer aggregation_ids21 = Integer.valueOf(jsonObject.getString("aggregation_id"));
                                                    double supply_chain_goods_settle_package_spec= Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(supply_chain_goods_settle_package_spec);
                                                    BigDecimal bigDecimal2 =new BigDecimal(voList.get(r).getReal_settlement_package_spec());

                                                    if (warehouse_id21==voList.get(r).getWarehouse_id()
                                                            && bigDecimal1.compareTo(bigDecimal2)==0 && aggregation_ids21==voList.get(r).getAggregation_id()){

                                                            //再判断明天的进销存库存是否需要新增
                                                            boolean need2= false;
                                                            for (int k = 0 ; k< recordsJSArray16.size();k++){
                                                                //存在已经生成的 明日初期库存明细数据 则过滤
                                                                JsonObject jsonObject2 =   recordsJSArray16.getJsonObject(i);
                                                                Integer warehouse_id212 = Integer.valueOf(jsonObject2.getString("warehouse_id"));
                                                                Integer aggregation_id212 = Integer.valueOf(jsonObject2.getString("aggregation_id"));
                                                                double supply_chain_goods_settle_package_spec2= Double.parseDouble(jsonObject2.getString("supply_chain_goods_settle_package_spec"));
                                                                BigDecimal bigDecimal12 =new BigDecimal(supply_chain_goods_settle_package_spec2);
                                                                if (warehouse_id212==voList.get(r).getWarehouse_id() && aggregation_id212==voList.get(r).getAggregation_id()
                                                                        && bigDecimal12.compareTo(bigDecimal2)==0 ){
                                                                    //存在则是过滤
                                                                    need2=true;
                                                                    break;
                                                                }
                                                            }if (!need2){
                                                                //需要新增 明日的数据
                                                            insertVo2Tomorrow.add(voList.get(r));
                                                            }
                                                            //再判断明天的进销存库存是否需要新增END
                                                        need=true;
                                                        break;
                                                    }
                                                }
                                                if (!need){
                                                    //需要新增的数据
                                                    if (insertVo2.size()==0){
                                                        if (voList.get(r).getType()==1){
                                                            //是聚集
                                                            String str = String.valueOf(voList.get(r).getId());
                                                            voList.get(r).setSupplierPickupGoodsInspectAcceptId(str);
                                                        }else {
                                                            //是销售区
                                                            String str = String.valueOf(voList.get(r).getId());
                                                            voList.get(r).setSalesSupplierPickupGoodsInspectAcceptId(str);
                                                        }
                                                        voList.get(r).setSupplier_pickup_goods_inspect_accept_codes(voList.get(r).getSupplier_pickup_goods_inspect_accept_code());
                                                        insertVo2.add(voList.get(r));
                                                    }else {
                                                        InitialBatchDetailVo vo =  voList.get(r);
                                                        boolean have = false;
                                                        for (InitialBatchDetailVo vo2 : insertVo2){
                                                            BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                            BigDecimal bigDecimal2 =new BigDecimal(vo2.getReal_settlement_package_spec());
                                                            if (vo.getWarehouse_id()==vo2.getWarehouse_id() && vo.getAggregation_id()==vo2.getAggregation_id()
                                                                    && bigDecimal1.compareTo(bigDecimal2)==0 ){
                                                                //有已经add的数据 不用再add  但是需要累计验收单ID
                                                                if (vo.getType()==1){
                                                                    //是聚集区域
                                                                    vo2.setSupplierPickupGoodsInspectAcceptId(vo2.getSupplierPickupGoodsInspectAcceptId()+","+vo.getId());
                                                                }else {
                                                                    //是销售区域
                                                                    vo2.setSalesSupplierPickupGoodsInspectAcceptId(vo2.getSalesSupplierPickupGoodsInspectAcceptId()+","+vo.getId());
                                                                }
                                                                vo2.setSupplier_pickup_goods_inspect_accept_codes(vo2.getSupplier_pickup_goods_inspect_accept_codes()+","+vo.getSupplier_pickup_goods_inspect_accept_code());
                                                                have=true;
                                                                break;
                                                            }
                                                        }
                                                        if (!have){
                                                            //需要add
                                                            if (vo.getType()==1){
                                                                //是聚集
                                                                String str = String.valueOf(vo.getId());
                                                                vo.setSupplierPickupGoodsInspectAcceptId(str);
                                                            }else {
                                                                //是销售区
                                                                String str = String.valueOf(vo.getId());
                                                                vo.setSalesSupplierPickupGoodsInspectAcceptId(str);
                                                            }
                                                            vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                            insertVo2.add(vo);
                                                        }
                                                    }
                                                }
                                            }
                                        }else {
                                            //不存的直接新增
                                            for (InitialBatchDetailVo vo : voList){
                                                if (insertVo2.size()==0){
                                                    if (vo.getType()==1){
                                                        //是聚集
                                                        String str = String.valueOf(vo.getId());
                                                        vo.setSupplierPickupGoodsInspectAcceptId(str);
                                                    }else {
                                                        //是销售区
                                                        String str = String.valueOf(vo.getId());
                                                        vo.setSalesSupplierPickupGoodsInspectAcceptId(str);
                                                    }
                                                    vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                    insertVo2.add(vo);
                                                }else {
                                                    boolean have = false;
                                                    for (InitialBatchDetailVo vo2 : insertVo2){
                                                        BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                        BigDecimal bigDecimal2 =new BigDecimal(vo2.getReal_settlement_package_spec());
                                                        if (vo.getWarehouse_id()==vo2.getWarehouse_id() && vo.getAggregation_id()==vo2.getAggregation_id()
                                                        && bigDecimal1.compareTo(bigDecimal2)==0 ){
                                                            //有已经add的数据 不用再add  但是需要累计验收单ID
                                                            if (vo2.getType()==1){
                                                                //是聚集区域
                                                                vo2.setSupplierPickupGoodsInspectAcceptId(vo2.getSupplierPickupGoodsInspectAcceptId()+","+vo.getId());
                                                            }else {
                                                                //是销售区域
                                                                vo2.setSalesSupplierPickupGoodsInspectAcceptId(vo2.getSalesSupplierPickupGoodsInspectAcceptId()+","+vo.getId());
                                                            }
                                                            vo2.setSupplier_pickup_goods_inspect_accept_codes(vo2.getSupplier_pickup_goods_inspect_accept_codes()+","+vo.getSupplier_pickup_goods_inspect_accept_code());
                                                            have=true;
                                                            break;
                                                        }
                                                    }
                                                    if (!have){
                                                        //需要add
                                                        if (vo.getType()==1){
                                                            //是聚集
                                                            String str = String.valueOf(vo.getId());
                                                            vo.setSupplierPickupGoodsInspectAcceptId(str);
                                                        }else {
                                                            //是销售区
                                                            String str = String.valueOf(vo.getId());
                                                            vo.setSalesSupplierPickupGoodsInspectAcceptId(str);
                                                        }
                                                        vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                        insertVo2.add(vo);
                                                    }
                                                }
                                            }
                                        }

                                        //斤价管理表头数据生成
                                        if (recordsJSArray5.size()>0){
                                            //存在已经生成的库存头数据 则过滤
                                            for (int r = 0 ; r<voList.size();r++){
                                                boolean need= false;
                                                for (int i = 0 ; i< recordsJSArray5.size();i++){
                                                    JsonObject jsonObject =   recordsJSArray5.getJsonObject(i);
                                                    Integer warehouse_id21 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    Integer aggregation_ids21 = Integer.valueOf(jsonObject.getString("aggregation_id"));
                                                    String goods_batch_code21 = jsonObject.getString("goods_batch_code");
                                                    double supply_chain_goods_settle_package_spec= Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(supply_chain_goods_settle_package_spec);
                                                    BigDecimal bigDecimal2 =new BigDecimal(voList.get(r).getReal_settlement_package_spec());

                                                    if (warehouse_id21==voList.get(r).getWarehouse_id()
                                                            && bigDecimal1.compareTo(bigDecimal2)==0 && aggregation_ids21==voList.get(r).getAggregation_id()
                                                    && goods_batch_code21.equals(voList.get(r).getGoods_batch_code())){
                                                        need=true;
                                                        break;
                                                    }
                                                }
                                                if (!need){
                                                    //需要新增的数据
                                                    if (insertVo3.size()==0){
                                                        voList.get(r).setSupplier_pickup_goods_inspect_accept_codes(voList.get(r).getSupplier_pickup_goods_inspect_accept_code());
                                                        insertVo3.add(voList.get(r));
                                                    }else {
                                                        InitialBatchDetailVo vo =  voList.get(r);
                                                        boolean have = false;
                                                        for (InitialBatchDetailVo vo3 : insertVo3){
                                                            BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                            BigDecimal bigDecimal2 =new BigDecimal(vo3.getReal_settlement_package_spec());
                                                            int type = vo.getType();
                                                            if (vo.getWarehouse_id()==vo3.getWarehouse_id() && vo.getAggregation_id()==vo3.getAggregation_id() && bigDecimal1.compareTo(bigDecimal2)==0 &&
                                                                    vo.getGoods_batch_code().equals(vo3.getGoods_batch_code())){
                                                                //有已经add的数据 不用再add
                                                                vo3.setSupplier_pickup_goods_inspect_accept_codes(vo3.getSupplier_pickup_goods_inspect_accept_codes()+","+vo.getSupplier_pickup_goods_inspect_accept_code());

                                                                have=true;
                                                                break;
                                                            }
                                                        }
                                                        if (!have){
                                                            //需要add
                                                            vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                            insertVo3.add(vo);
                                                        }
                                                    }
                                                }
                                            }
                                        }else {
                                            //不存的直接新增
                                            for (InitialBatchDetailVo vo : voList){
                                                if (insertVo3.size()==0){
                                                    vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                    insertVo3.add(vo);
                                                }else {
                                                    boolean have = false;
                                                    for (InitialBatchDetailVo vo3 : insertVo3){
                                                        BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                        BigDecimal bigDecimal2 =new BigDecimal(vo3.getReal_settlement_package_spec());
                                                        if (vo.getWarehouse_id()==vo3.getWarehouse_id() && vo.getAggregation_id()==vo3.getAggregation_id()
                                                                && bigDecimal1.compareTo(bigDecimal2)==0 && vo3.getGoods_batch_code().equals(vo.getGoods_batch_code())){
                                                            //有已经add的数据 不用再add
                                                            vo3.setSupplier_pickup_goods_inspect_accept_codes(vo3.getSupplier_pickup_goods_inspect_accept_codes()+","+vo.getSupplier_pickup_goods_inspect_accept_code());
                                                            have=true;
                                                            break;
                                                        }
                                                    }
                                                    if (!have){
                                                        //需要add
                                                        vo.setSupplier_pickup_goods_inspect_accept_codes(vo.getSupplier_pickup_goods_inspect_accept_code());
                                                        insertVo3.add(vo);
                                                    }
                                                }
                                            }
                                        }


                                        //毛利及提成表头数据生成
                                        if (recordsJSArray6.size()>0){
                                            //存在已经生成的库存头数据 则过滤
                                            for (int r = 0 ; r<voList.size();r++){
                                                boolean need= false;
                                                for (int i = 0 ; i< recordsJSArray6.size();i++){
                                                    JsonObject jsonObject =   recordsJSArray6.getJsonObject(i);
                                                    Integer warehouse_id21 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    Integer supply_chain_goods_ids21 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    Integer supplier_ids21 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    String supplier_pickup_goods_inspect_accept_codes21 = jsonObject.getString("supplier_pickup_goods_inspect_accept_code");
                                                    double supply_chain_goods_settle_package_spec= Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(supply_chain_goods_settle_package_spec);
                                                    BigDecimal bigDecimal2 =new BigDecimal(voList.get(r).getReal_settlement_package_spec());

                                                    if (warehouse_id21==voList.get(r).getWarehouse_id()
                                                            && bigDecimal1.compareTo(bigDecimal2)==0 && supplier_ids21==voList.get(r).getSupplier_id() && supply_chain_goods_ids21==voList.get(r).getSupply_chain_goods_id()
                                                    && supplier_pickup_goods_inspect_accept_codes21.equals(voList.get(r).getSupplier_pickup_goods_inspect_accept_code())){
                                                        need=true;
                                                        break;
                                                    }
                                                }
                                                if (!need){
                                                    //需要新增的数据
                                                    if (insertVo4.size()==0){
                                                        insertVo4.add(voList.get(r));
                                                    }else {
                                                        InitialBatchDetailVo vo =  voList.get(r);
                                                        boolean have = false;
                                                        for (InitialBatchDetailVo vo3 : insertVo4){
                                                            BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                            BigDecimal bigDecimal2 =new BigDecimal(vo3.getReal_settlement_package_spec());
                                                            if (vo.getWarehouse_id()==vo3.getWarehouse_id() && vo.getSupplier_id()==vo3.getSupplier_id()&& vo.getSupply_chain_goods_id()==vo3.getSupply_chain_goods_id()
                                                                    && bigDecimal1.compareTo(bigDecimal2)==0 && vo.getSupplier_pickup_goods_inspect_accept_code().equals(vo3.getSupplier_pickup_goods_inspect_accept_code())){
                                                                //有已经add的数据 不用再add
                                                                have=true;
                                                                break;
                                                            }
                                                        }
                                                        if (!have){
                                                            //需要add
                                                            insertVo4.add(vo);
                                                        }
                                                    }
                                                }
                                            }
                                        }else {
                                            //不存的直接新增
                                            for (InitialBatchDetailVo vo : voList){
                                                if (insertVo4.size()==0){
                                                    insertVo4.add(vo);
                                                }else {
                                                    boolean have = false;
                                                    for (InitialBatchDetailVo vo3 : insertVo4){
                                                        BigDecimal bigDecimal1 =new BigDecimal(vo.getReal_settlement_package_spec());
                                                        BigDecimal bigDecimal2 =new BigDecimal(vo3.getReal_settlement_package_spec());
                                                        if (vo.getWarehouse_id()==vo3.getWarehouse_id() && vo.getSupplier_id()==vo3.getSupplier_id()&& vo.getSupply_chain_goods_id()==vo3.getSupply_chain_goods_id()
                                                                && bigDecimal1.compareTo(bigDecimal2)==0 && vo3.getSupplier_pickup_goods_inspect_accept_code().equals(vo.getSupplier_pickup_goods_inspect_accept_code())){
                                                            //有已经add的数据 不用再add
                                                            have=true;
                                                            break;
                                                        }
                                                    }
                                                    if (!have){
                                                        //需要add
                                                        insertVo4.add(vo);
                                                    }
                                                }
                                            }
                                        }

                                        //更新维度下重复的数据satr
                                        List<InitialBatchDetailVo> insertVo01 = new ArrayList<InitialBatchDetailVo>();
                                        List<InitialBatchDetailVo> updateVo01 = new ArrayList<InitialBatchDetailVo>();
                                        for (InitialBatchDetailVo vo : insertVo){
                                            int b01=vo.getWarehouse_id();
                                            int b02 =vo.getSupplier_id();
                                            int b03=vo.getSupply_chain_goods_id();
                                            String b04=vo.getGoods_batch_code();
                                            double b05 =vo.getSupply_chain_goods_weight_package_spec();
                                            BigDecimal bigDecimal05 = new BigDecimal(b05);
                                            if (insertVo01.size()==0){
                                                insertVo01.add(vo);
                                            }else {
                                                for (InitialBatchDetailVo vo01 : insertVo01){
                                                    int a01=vo01.getWarehouse_id();
                                                    int a02 =vo01.getSupplier_id();
                                                    int a03=vo01.getSupply_chain_goods_id();
                                                    String a04=vo01.getGoods_batch_code();
                                                    double a05 =vo01.getSupply_chain_goods_weight_package_spec();
                                                    BigDecimal bigDecimala05 = new BigDecimal(a05);
                                                    if (b01==a01 && b02==a02 && b03==a03 && b04.equals(a04) && bigDecimal05.compareTo(bigDecimala05)==0){
                                                        Integer total_number = vo.getTotal_number();
                                                        double total_weight = vo.getTotal_weight();
                                                        BigDecimal j = new BigDecimal(total_weight);
                                                        Integer loss_number = vo.getLoss_number();
                                                        double loss_weight = vo.getLoss_weight();
                                                        BigDecimal j01 = new BigDecimal(loss_weight);
                                                        Integer profit_loss_number = vo.getProfit_loss_number();
                                                        double profit_loss_weight = vo.getProfit_loss_weight();
                                                        BigDecimal j02 = new BigDecimal(profit_loss_weight);

                                                        Integer total_number01 = vo01.getTotal_number();
                                                        double total_weight01 = vo01.getTotal_weight();
                                                        BigDecimal k = new BigDecimal(total_weight01);
                                                        Integer loss_number01 = vo01.getLoss_number();
                                                        double loss_weight01 = vo01.getLoss_weight();
                                                        BigDecimal k01 = new BigDecimal(loss_weight01);
                                                        Integer profit_loss_number01 = vo01.getProfit_loss_number();
                                                        double profit_loss_weight01 = vo01.getProfit_loss_weight();
                                                        BigDecimal k02 = new BigDecimal(profit_loss_weight01);

                                                        vo01.setTotal_number(total_number+total_number01);
                                                        vo01.setLoss_number(loss_number+loss_number01);
                                                        vo01.setProfit_loss_number(profit_loss_number+profit_loss_number01);
                                                        vo01.setTotal_weight(j.add(k).doubleValue());
                                                        vo01.setLoss_weight(j01.add(k01).doubleValue());
                                                        vo01.setProfit_loss_weight(j02.add(k02).doubleValue());
                                                    }else {
                                                        insertVo01.add(vo);
                                                    }
                                                }
                                            }
                                        }
                                        for (InitialBatchDetailVo vo : updateVo){
                                            int b01=vo.getWarehouse_id();
                                            int b02 =vo.getSupplier_id();
                                            int b03=vo.getSupply_chain_goods_id();
                                            String b04=vo.getGoods_batch_code();
                                            double b05 =vo.getSupply_chain_goods_weight_package_spec();
                                            BigDecimal bigDecimal05 = new BigDecimal(b05);
                                            if (insertVo01.size()==0){
                                                insertVo01.add(vo);
                                            }else {
                                                for (InitialBatchDetailVo vo01 : updateVo01){
                                                    int a01=vo01.getWarehouse_id();
                                                    int a02 =vo01.getSupplier_id();
                                                    int a03=vo01.getSupply_chain_goods_id();
                                                    String a04=vo01.getGoods_batch_code();
                                                    double a05 =vo01.getSupply_chain_goods_weight_package_spec();
                                                    BigDecimal bigDecimala05 = new BigDecimal(a05);
                                                    if (b01==a01 && b02==a02 && b03==a03 && b04.equals(a04) && bigDecimal05.compareTo(bigDecimala05)==0){
                                                        Integer total_number = vo.getTotal_number();
                                                        double total_weight = vo.getTotal_weight();
                                                        BigDecimal j = new BigDecimal(total_weight);
                                                        Integer loss_number = vo.getLoss_number();
                                                        double loss_weight = vo.getLoss_weight();
                                                        BigDecimal j01 = new BigDecimal(loss_weight);
                                                        Integer profit_loss_number = vo.getProfit_loss_number();
                                                        double profit_loss_weight = vo.getProfit_loss_weight();
                                                        BigDecimal j02 = new BigDecimal(profit_loss_weight);

                                                        Integer total_number01 = vo01.getTotal_number();
                                                        double total_weight01 = vo01.getTotal_weight();
                                                        BigDecimal k = new BigDecimal(total_weight01);
                                                        Integer loss_number01 = vo01.getLoss_number();
                                                        double loss_weight01 = vo01.getLoss_weight();
                                                        BigDecimal k01 = new BigDecimal(loss_weight01);
                                                        Integer profit_loss_number01 = vo01.getProfit_loss_number();
                                                        double profit_loss_weight01 = vo01.getProfit_loss_weight();
                                                        BigDecimal k02 = new BigDecimal(profit_loss_weight01);

                                                        vo01.setTotal_number(total_number+total_number01);
                                                        vo01.setLoss_number(loss_number+loss_number01);
                                                        vo01.setProfit_loss_number(profit_loss_number+profit_loss_number01);
                                                        vo01.setTotal_weight(j.add(k).doubleValue());
                                                        vo01.setLoss_weight(j01.add(k01).doubleValue());
                                                        vo01.setProfit_loss_weight(j02.add(k02).doubleValue());
                                                    }else {
                                                        updateVo01.add(vo);
                                                    }
                                                }
                                            }
                                        }
                                        //end



                                        List<Tuple> tupleList1 = new ArrayList<>();
                                        List<Tuple> tupleList2 = new ArrayList<>();
                                        List<Tuple> tupleList3 = new ArrayList<>();
                                        List<Tuple> tupleList4 = new ArrayList<>();
                                        List<Tuple> tupleList5 = new ArrayList<>();
                                        List<Future> futures2= new ArrayList<>();
                                        LocalDate localDate2 = LocalDate.parse(date2, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                        for (InitialBatchDetailVo vo : insertVo01){
                                           Integer total_number = vo.getTotal_number();
                                           double total_weight = vo.getTotal_weight();
                                           Integer loss_number = vo.getLoss_number();
                                            double loss_weight = vo.getLoss_weight();
                                           Integer profit_loss_number = vo.getProfit_loss_number();
                                            double profit_loss_weight = vo.getProfit_loss_weight();
                                            //销售退货
                                            int retrun_warehouse_number0 =0;
                                            double retrun_warehouse_weight0 =0.00;
                                            int parme1 = vo.getSupply_chain_goods_id();
                                            double parme2 = vo.getReal_settlement_package_spec();
                                            BigDecimal bigParme2 = new BigDecimal(parme2);
                                            int parme3 = vo.getWarehouse_id();
                                            String parm4 =vo.getGoods_batch_code();
                                            int parm5 = vo.getSupplier_id();
                                            if (recordsJSArray8.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray8.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    String exist4 = jsonObject.getString("goods_batch_codes");
                                                    int exist5 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3 && exist4.equals(parm4) &&
                                                     exist5==parm5){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(retrun_warehouse_weight0);
                                                        //retrun_warehouse_number 和 retrun_warehouse_weight
                                                        double c1 = Double.parseDouble(jsonObject.getString("retrun_warehouse_number")==null? "0":jsonObject.getString("retrun_warehouse_number"));
                                                        int retrun_warehouse_number2 =(int) Math.floor(c1);
                                                        double retrun_warehouse_weight2 = Double.parseDouble(jsonObject.getString("retrun_warehouse_weight")==null? "0":jsonObject.getString("retrun_warehouse_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(retrun_warehouse_weight2);
                                                        retrun_warehouse_number0 =  retrun_warehouse_number0+retrun_warehouse_number2;
                                                        retrun_warehouse_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //车次配送
                                            int shift_delivery_plan_completion_number0 =0;
                                            double shift_delivery_plan_completion_weight0 =0.00;
                                            if (recordsJSArray9.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray9.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    String exist4 = jsonObject.getString("goods_batch_codes");
                                                    int exist5 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3 && exist4.equals(parm4) &&
                                                            exist5==parm5){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(shift_delivery_plan_completion_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("shift_delivery_plan_completion_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("shift_delivery_plan_completion_number")==null? "0":jsonObject.getString("shift_delivery_plan_completion_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("shift_delivery_plan_completion_weight")==null? "0":jsonObject.getString("shift_delivery_plan_completion_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        shift_delivery_plan_completion_number0 =  shift_delivery_plan_completion_number0+number2;
                                                        shift_delivery_plan_completion_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //自提完工
                                            int pickup_number0 =0;
                                            double pickup_weight0 =0.00;
                                            if (recordsJSArray10.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray10.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    String exist4 = jsonObject.getString("goods_batch_codes");
                                                    int exist5 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3 && exist4.equals(parm4) &&
                                                            exist5==parm5){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(pickup_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("pickup_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("pickup_number")==null? "0":jsonObject.getString("pickup_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("pickup_weight")==null? "0":jsonObject.getString("pickup_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        pickup_number0 =  pickup_number0+number2;
                                                        pickup_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //采购退货
                                            int purchase_return_number0 =0;
                                            double purchase_return_weight0 =0.00;
                                            if (recordsJSArray15.size()>0){
                                                for (int r =0 ; r < recordsJSArray15.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray10.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    String exist4 = jsonObject.getString("goods_batch_codes");
                                                    int exist5 = Integer.valueOf(jsonObject.getString("supplier_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3 && exist4.equals(parm4) &&
                                                            exist5==parm5){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(purchase_return_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("purchase_return_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("purchase_return_number")==null? "0":jsonObject.getString("purchase_return_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("purchase_return_weight")==null? "0":jsonObject.getString("purchase_return_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        purchase_return_number0 = purchase_return_number0 +number2;
                                                        purchase_return_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }

                                            //
                                            BigDecimal bigDecimal1002= new BigDecimal(retrun_warehouse_weight0);
                                            BigDecimal bigDecimal1004= new BigDecimal(shift_delivery_plan_completion_weight0);
                                            BigDecimal bigDecimal1006= new BigDecimal(pickup_weight0);
                                            BigDecimal bigDecimal10012= new BigDecimal(purchase_return_weight0);

                                            Integer end_number = total_number-loss_number+profit_loss_number+retrun_warehouse_number0-shift_delivery_plan_completion_number0-pickup_number0-purchase_return_number0;
                                            BigDecimal bigDecimal1 = new BigDecimal(total_weight);
                                            BigDecimal bigDecimal11 = new BigDecimal(loss_weight);
                                            BigDecimal bigDecimal12 = new BigDecimal(profit_loss_weight);
                                            double end_weight=bigDecimal1.subtract(bigDecimal11).add(bigDecimal12).add(bigDecimal1002).subtract(bigDecimal1004).subtract(bigDecimal1006).subtract(bigDecimal10012).doubleValue();
                                            //当天的
                                            if (vo.getType()==1){
                                                tupleList1.add( Tuple.of(vo.getSupply_chain_goods_id(),vo.getReal_settlement_package_spec(),vo.getGoods_batch_code(),vo.getSupplier_id(),0.00,0.00,create_user2,create_user2,
                                                        vo.getWarehouse_id(),localDate,vo.getTotal_number(),vo.getTotal_weight(),vo.getLoss_number(),vo.getLoss_weight(),vo.getProfit_loss_number(),vo.getProfit_loss_weight(),vo.getAggregation_id(),
                                                        end_number,end_weight,vo.getId(),0));
                                            }else {
                                                tupleList1.add( Tuple.of(vo.getSupply_chain_goods_id(),vo.getReal_settlement_package_spec(),vo.getGoods_batch_code(),vo.getSupplier_id(),0.00,0.00,create_user2,create_user2,
                                                        vo.getWarehouse_id(),localDate,vo.getTotal_number(),vo.getTotal_weight(),vo.getLoss_number(),vo.getLoss_weight(),vo.getProfit_loss_number(),vo.getProfit_loss_weight(),vo.getAggregation_id(),
                                                        end_number,end_weight,0,vo.getSaleId()));
                                            }
                                        }
                                        for (InitialBatchDetailVo vo : updateVo01){
                                            Integer total_number = vo.getTotal_number();
                                            double total_weight = vo.getTotal_weight();
                                            Integer loss_number = vo.getLoss_number();
                                            double loss_weight = vo.getLoss_weight();
                                            Integer profit_loss_number = vo.getProfit_loss_number();
                                            double profit_loss_weight = vo.getProfit_loss_weight();
                                            //销售退货
                                            int retrun_warehouse_number0 =0;
                                            double retrun_warehouse_weight0 =0.00;
                                            int parme1 = vo.getSupply_chain_goods_id();
                                            double parme2 = vo.getReal_settlement_package_spec();
                                            BigDecimal bigParme2 = new BigDecimal(parme2);
                                            int parme3 = vo.getWarehouse_id();
                                            int parme4 = vo.getAggregation_id();
                                            if (recordsJSArray8.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray8.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(retrun_warehouse_weight0);
                                                        //retrun_warehouse_number 和 retrun_warehouse_weight
//                                                        int retrun_warehouse_number2 = Integer.parseInt(jsonObject.getString("retrun_warehouse_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("retrun_warehouse_number")==null? "0":jsonObject.getString("retrun_warehouse_number"));
                                                        int retrun_warehouse_number2 =(int) Math.floor(c1);
                                                        double retrun_warehouse_weight2 = Double.parseDouble(jsonObject.getString("retrun_warehouse_weight")==null? "0":jsonObject.getString("retrun_warehouse_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(retrun_warehouse_weight2);
                                                        retrun_warehouse_number0 =  retrun_warehouse_number0+retrun_warehouse_number2;
                                                        retrun_warehouse_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //车次配送
                                            int shift_delivery_plan_completion_number0 =0;
                                            double shift_delivery_plan_completion_weight0 =0.00;
                                            if (recordsJSArray9.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray9.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec")==null? "0":jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(shift_delivery_plan_completion_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("shift_delivery_plan_completion_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("shift_delivery_plan_completion_number")==null? "0":jsonObject.getString("shift_delivery_plan_completion_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("shift_delivery_plan_completion_weight")==null? "0":jsonObject.getString("shift_delivery_plan_completion_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        shift_delivery_plan_completion_number0 =  shift_delivery_plan_completion_number0+number2;
                                                        shift_delivery_plan_completion_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //自提完工
                                            int pickup_number0 =0;
                                            double pickup_weight0 =0.00;
                                            if (recordsJSArray10.size()>0){
                                                for (int r =0 ; r < recordsJSArray8.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray10.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(pickup_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("pickup_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("pickup_number")==null? "0":jsonObject.getString("pickup_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("pickup_weight")==null? "0":jsonObject.getString("pickup_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        pickup_number0 =  pickup_number0+number2;
                                                        pickup_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }
                                            //采购退货
                                            int purchase_return_number0 =0;
                                            double purchase_return_weight0 =0.00;
                                            if (recordsJSArray15.size()>0){
                                                for (int r =0 ; r < recordsJSArray15.size();r++){
                                                    JsonObject jsonObject =  recordsJSArray10.getJsonObject(r);
                                                    int exist1 = Integer.valueOf(jsonObject.getString("supply_chain_goods_id"));
                                                    double exist2 = Double.parseDouble(jsonObject.getString("supply_chain_goods_settle_package_spec"));
                                                    BigDecimal bigExist2 = new BigDecimal(exist2);
                                                    int exist3 = Integer.valueOf(jsonObject.getString("warehouse_id"));
                                                    if (bigExist2.compareTo(bigParme2)==0 && exist1==parme1 && exist3==parme3){
                                                        //相对则是对应关系则 加
                                                        BigDecimal bigDecimal2=new BigDecimal(purchase_return_weight0);
                                                        //
//                                                        int number2 = Integer.parseInt(jsonObject.getString("purchase_return_number"));
                                                        double c1 = Double.parseDouble(jsonObject.getString("purchase_return_number")==null? "0":jsonObject.getString("purchase_return_number"));
                                                        int number2 =(int) Math.floor(c1);
                                                        double weight2 = Double.parseDouble(jsonObject.getString("purchase_return_weight")==null? "0":jsonObject.getString("purchase_return_weight"));
                                                        BigDecimal bigDecimal4=new BigDecimal(weight2);
                                                        purchase_return_number0 = purchase_return_number0 +number2;
                                                        purchase_return_weight0 =  bigDecimal2.add(bigDecimal4).doubleValue();
                                                    }
                                                }
                                            }

                                            //
                                            BigDecimal bigDecimal1002= new BigDecimal(retrun_warehouse_weight0);
                                            BigDecimal bigDecimal1004= new BigDecimal(shift_delivery_plan_completion_weight0);
                                            BigDecimal bigDecimal1006= new BigDecimal(pickup_weight0);
                                            BigDecimal bigDecimal10012= new BigDecimal(purchase_return_weight0);



                                            Integer end_number = total_number-loss_number+profit_loss_number+retrun_warehouse_number0-shift_delivery_plan_completion_number0-pickup_number0-purchase_return_number0;
                                            BigDecimal bigDecimal1 = new BigDecimal(total_weight);
                                            BigDecimal bigDecimal11 = new BigDecimal(loss_weight);
                                            BigDecimal bigDecimal12 = new BigDecimal(profit_loss_weight);
                                            double end_weight=bigDecimal1.subtract(bigDecimal11).add(bigDecimal12).add(bigDecimal1002).subtract(bigDecimal1004).subtract(bigDecimal1006).subtract(bigDecimal10012).doubleValue();
                                                Integer a111 =0;
                                                Integer a211 =0;
                                                if (vo.getId()==null || vo.getId()==0){
                                                    a111=0;
                                                }else {
                                                    a111=vo.getId();
                                                }
                                                if (vo.getSaleId()==null || vo.getSaleId()==0){
                                                    a211=0;
                                                }else {
                                                    a211=vo.getSaleId();
                                                }
                                                tupleList2.add( Tuple.of(vo.getTotal_number(),vo.getTotal_weight(),vo.getLoss_number(),vo.getLoss_weight(),vo.getProfit_loss_number(),
                                                        vo.getProfit_loss_weight(),end_number,end_weight,a111,
                                                        a211,0.00,0.00,vo.getInitialBatchDetaiId()));
                                        }
                                        for (InitialBatchDetailVo vo : insertVo2){
                                            //当天库存
                                            tupleList3.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getSalesSupplierPickupGoodsInspectAcceptId(),
                                                    vo.getSupplierPickupGoodsInspectAcceptId(),vo.getClass_lv1_id(),vo.getClass_lv2_id(),vo.getVariety_id(),vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_codes(),vo.getSupply_chain_goods_weight_package_spec()));
                                            //明天库存
                                            tupleList3.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate2,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getSalesSupplierPickupGoodsInspectAcceptId(),
                                                    vo.getSupplierPickupGoodsInspectAcceptId(),vo.getClass_lv1_id(),vo.getClass_lv2_id(),vo.getVariety_id(),vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_codes(),vo.getSupply_chain_goods_weight_package_spec()));
                                        }
                                        for (InitialBatchDetailVo vo : insertVo2Tomorrow){
                                            //明天
                                            tupleList3.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate2,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getSalesSupplierPickupGoodsInspectAcceptId(),
                                                    vo.getSupplierPickupGoodsInspectAcceptId(),vo.getClass_lv1_id(),vo.getClass_lv2_id(),vo.getVariety_id(),vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_codes(),vo.getSupply_chain_goods_weight_package_spec()));
                                        }
                                        for (InitialBatchDetailVo vo : insertVo3){
                                            //当天库存
                                            tupleList4.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getGoods_batch_code(),vo.getClass_lv1_id(),vo.getClass_lv2_id(),vo.getVariety_id(),vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_codes(),
                                                    vo.getSupply_chain_goods_weight_package_spec()));
                                            //明天库存
                                            tupleList4.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate2,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getGoods_batch_code(),vo.getClass_lv1_id(),vo.getClass_lv2_id(),vo.getVariety_id(),vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_codes(),
                                                    vo.getSupply_chain_goods_weight_package_spec()));
                                        }
                                        for (InitialBatchDetailVo vo : insertVo4){
                                            //当天库存
                                            tupleList5.add( Tuple.of(vo.getWarehouse_id(),vo.getAggregation_id(),localDate,vo.getReal_settlement_package_spec(),create_user2,create_user2,vo.getGoods_batch_code(),vo.getGoods_gather_area_id(),
                                                    vo.getBig_area_id(),vo.getSite_id(),vo.getSupplier_pickup_goods_inspect_accept_code(),vo.getTotal_weight(),vo.getId(),vo.getClass_lv1_id(),vo.getCif_gross_profit_margin(),
                                                    vo.getPartner_name(),vo.getGross_profit_commission_processing_center_manager(),vo.getSupply_chain_goods_id()));

                                        }

                                        if (tupleList1.size()>0){
                                            String insert_sql = "INSERT INTO initial_batch_detail(supply_chain_goods_id,supply_chain_goods_settle_package_spec,goods_batch_code,supplier_id,inventory_number,inventory_weight, " +
                                                    " create_user,update_user,warehouse_id,time_line,accept_number,accept_weight,loss_number,loss_weight,profit_loss_number,profit_loss_weight, " +
                                                    "aggregation_id,end_inventory_number,end_inventory_weight,supplier_pickup_goods_inspect_accept_id,sales_supplier_pickup_goods_inspect_accept_id" +
                                                    " ) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16,$17,$18,$19,$20,$21) RETURNING id";
                                            Future<RowSet<Row>>  insertSqlBatchFuture = this.commonRepository.insertOrUpdateBatch(conn, insert_sql, tupleList1, "insertSqlBatchFuture");
                                            futures2.add(insertSqlBatchFuture);
                                            logger.info("insertSqlBatchFuture size: {}", tupleList1.size());
                                        }

                                        if (tupleList2.size()>0){
                                            String update_sql2 ="update initial_batch_detail set accept_number=$1,accept_weight=$2,loss_number=$3,loss_weight=$4,profit_loss_number=$5,profit_loss_weight=$6," +
                                                    "end_inventory_number=$7, end_inventory_weight=$8,supplier_pickup_goods_inspect_accept_id=$9,sales_supplier_pickup_goods_inspect_accept_id=$10,inventory_number=$11,inventory_weight=$12 " +
                                                    " where id=$13 ";
                                            Future<RowSet<Row>>  updateSqlBatchFuture = this.commonRepository.insertOrUpdateBatch(conn, update_sql2, tupleList2, "updateSqlBatchFuture");
                                            futures2.add(updateSqlBatchFuture);
                                            logger.info("updateSqlBatchFuture size: {}", tupleList2.size());
                                        }

                                        if (tupleList3.size()>0){
                                            String insert_sql2 = "INSERT INTO supplier_batch_goods_psi(warehouse_id,aggregation_id, time_line,supply_chain_goods_settle_package_spec,create_user,update_user,sales_supplier_pickup_goods_inspect_accept_id,supplier_pickup_goods_inspect_accept_id, " +
                                                    " class_lv1_id,class_lv2_id,variety_id,big_area_id,site_id,supplier_pickup_goods_inspect_accept_codes ,supply_chain_goods_weight_package_spec) VALUES($1, $2, $3, $4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) RETURNING id";
                                            Future<RowSet<Row>>  insertSupplierBatchGoodsPsiBatchFuture = this.commonRepository.insertOrUpdateBatch(conn, insert_sql2, tupleList3, "insertSupplierBatchGoodsPsiBatchFuture");
                                            futures2.add(insertSupplierBatchGoodsPsiBatchFuture);
                                            logger.info("insertSupplierBatchGoodsPsiBatchFuture size: {}", tupleList3.size());
                                        }

                                        if (tupleList4.size()>0){
                                            String insert_sql3 = "INSERT INTO supplier_batch_goods_cost_price(warehouse_id,aggregation_id, time_line,supply_chain_goods_settle_package_spec,create_user,update_user,goods_batch_code,class_lv1_id,class_lv2_id, " +
                                                    " variety_id,big_area_id,site_id,supplier_pickup_goods_inspect_accept_codes,supply_chain_goods_weight_package_spec ) VALUES($1, $2, $3, $4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) RETURNING id";
                                            Future<RowSet<Row>>  insertSupplierBatchGoodsCostPriceFuture = this.commonRepository.insertOrUpdateBatch(conn, insert_sql3, tupleList4, "insertSupplierBatchGoodsCostPriceFuture");
                                            futures2.add(insertSupplierBatchGoodsCostPriceFuture);
                                            logger.info("insertSupplierBatchGoodsPsiBatchFuture size: {}", tupleList4.size());
                                        }

                                        if (tupleList5.size()>0){
                                            String insert_sql4 = "INSERT INTO goods_gross_profit_commission_detail(warehouse_id,aggregation_id, time_line,supply_chain_goods_settle_package_spec,create_user,update_user,goods_batch_code,goods_gather_area_id, " +
                                                    " big_area_id,site_id,supplier_pickup_goods_inspect_accept_code,inspect_accept_total_weight,supplier_pickup_goods_inspect_accept_detail_id,class_lv1_id,cif_gross_profit_margin,partner_name,gross_profit_commission_processing_center_manager," +
                                                    " supply_chain_goods_id )  " +
                                                    " VALUES($1, $2, $3, $4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18) RETURNING id";
                                            Future<RowSet<Row>>  insertGoodsGrossProfitCommissionDetailFuture = this.commonRepository.insertOrUpdateBatch(conn, insert_sql4, tupleList5, "insertGoodsGrossProfitCommissionDetailFuture");
                                            futures2.add(insertGoodsGrossProfitCommissionDetailFuture);
                                            logger.info("insertGoodsGrossProfitCommissionDetailFuture size: {}", tupleList5.size());
                                        }
                                        if (futures2.size() > 0) {
                                            logger.info("futures2.size(): {}", futures2.size());
                                            CompositeFuture.join(futures2).onComplete(ar4 -> {
                                                if (ar4.succeeded()) {
                                                    JsonObject insert_or_update_result = new JsonObject();
                                                    logger.info("insert_or_update_result: {}",ar4.cause());
                                                    responseJSObj.put("msg", "生成成功");
                                                    promise.complete(responseJSObj);
                                                } else {
                                                    responseJSObj.put("msg", responseJSObj.getString("msg") + "; " + ar4.cause().getMessage());
                                                    promise.complete(responseJSObj);
                                                }
                                            });
                                        }
                                    }else {
                                        logger.info("获取记录数据发生错误: {}", ar3.cause().getMessage());
                                        promise.complete(CommonUtils.createExceptionJsonObject(ar3, "getfuture3ORfuture4", "查询数据失败"));
                                    }
                                }). onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsSalesSupplierOrgetRecordsSupplier", "查询数据失败！")));
                            }else {
                                //销售区域验收单 和聚集区域验收单 查询不到数据则不需要生成库存相关数据
                                responseJSObj.put("code",0).put("msg", "没有可以生成库存的数据验收单!");
                                promise.complete(responseJSObj);
                            }
                        }else {
                            logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                            promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getRecordsSalesSupplierOrgetRecordsSupplier", "查询数据失败"));
                        }

                    }). onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getRecordsSalesSupplierOrgetRecordsSupplier", "查询数据失败！")));
                }).
                onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getSupplierBatchGoodspsiRecords", "数据库连接失败")));
        return promise.future();
    }

}
